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
|
---|---|---|---|---|---|---|---|---|
10059850 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using Avalonia.Utilities;
using AvaloniaEdit.Rendering;
using TextLine = Avalonia.Media.TextFormatting.TextLine;
using TextRun = Avalonia.Media.TextFormatting.TextRun;
using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
public static class TextFormatterFactory
{
/// <summary>
/// Creates formatted text.
/// </summary>
/// </summary>
/// <param name="element">The owner element. The text formatter setting are read from this element.</param>
/// <param name="text">The text.</param>
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
{
var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
var textSource = new SimpleTextSource(text, defaultProperties);
return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
}
private readonly struct SimpleTextSource : ITextSource
{
private readonly ReadOnlySlice<char> _text;
private readonly TextRunProperties _defaultProperties;
public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
{
_text = text;
_defaultProperties = defaultProperties;
}
public TextRun GetTextRun(int textSourceIndex)
{
if (textSourceIndex < _text.Length)
{
return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
}
if (textSourceIndex > _text.Length)
{
return null;
}
return new TextEndOfParagraph(1);
}
}
}
}
}
<MSG> Redo Avalonia port of AvalonEdit.Rendering
<DFF> @@ -16,21 +16,27 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
+using System;
+using System.Globalization;
+using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
-using Avalonia.Utilities;
-using AvaloniaEdit.Rendering;
-using TextLine = Avalonia.Media.TextFormatting.TextLine;
-using TextRun = Avalonia.Media.TextFormatting.TextRun;
-using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
- /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
- /// </summary>
- public static class TextFormatterFactory
+ /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
+ /// </summary>
+ static class TextFormatterFactory
{
+ /// <summary>
+ /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
+ /// </summary>
+ public static TextFormatter Create(Control owner)
+ {
+ return TextFormatter.Current;
+ }
+
/// <summary>
/// Creates formatted text.
/// </summary>
@@ -40,41 +46,26 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
- {
- var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
- var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
-
- var textSource = new SimpleTextSource(text, defaultProperties);
-
- return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
- }
-
- private readonly struct SimpleTextSource : ITextSource
+ public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
- private readonly ReadOnlySlice<char> _text;
- private readonly TextRunProperties _defaultProperties;
-
- public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
- {
- _text = text;
- _defaultProperties = defaultProperties;
- }
-
- public TextRun GetTextRun(int textSourceIndex)
- {
- if (textSourceIndex < _text.Length)
- {
- return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
- }
-
- if (textSourceIndex > _text.Length)
- {
- return null;
- }
+ if (element == null)
+ throw new ArgumentNullException(nameof(element));
+ if (text == null)
+ throw new ArgumentNullException(nameof(text));
+ if (typeface == default)
+ typeface = element.CreateTypeface();
+ if (emSize == null)
+ emSize = TextBlock.GetFontSize(element);
+ if (foreground == null)
+ foreground = TextBlock.GetForeground(element);
- return new TextEndOfParagraph(1);
- }
+ return new FormattedText(
+ text,
+ CultureInfo.CurrentCulture,
+ FlowDirection.LeftToRight,
+ typeface,
+ emSize.Value,
+ foreground);
}
}
}
| 32 | Redo Avalonia port of AvalonEdit.Rendering | 41 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059851 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using Avalonia.Utilities;
using AvaloniaEdit.Rendering;
using TextLine = Avalonia.Media.TextFormatting.TextLine;
using TextRun = Avalonia.Media.TextFormatting.TextRun;
using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
public static class TextFormatterFactory
{
/// <summary>
/// Creates formatted text.
/// </summary>
/// </summary>
/// <param name="element">The owner element. The text formatter setting are read from this element.</param>
/// <param name="text">The text.</param>
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
{
var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
var textSource = new SimpleTextSource(text, defaultProperties);
return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
}
private readonly struct SimpleTextSource : ITextSource
{
private readonly ReadOnlySlice<char> _text;
private readonly TextRunProperties _defaultProperties;
public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
{
_text = text;
_defaultProperties = defaultProperties;
}
public TextRun GetTextRun(int textSourceIndex)
{
if (textSourceIndex < _text.Length)
{
return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
}
if (textSourceIndex > _text.Length)
{
return null;
}
return new TextEndOfParagraph(1);
}
}
}
}
}
<MSG> Redo Avalonia port of AvalonEdit.Rendering
<DFF> @@ -16,21 +16,27 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
+using System;
+using System.Globalization;
+using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
-using Avalonia.Utilities;
-using AvaloniaEdit.Rendering;
-using TextLine = Avalonia.Media.TextFormatting.TextLine;
-using TextRun = Avalonia.Media.TextFormatting.TextRun;
-using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
- /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
- /// </summary>
- public static class TextFormatterFactory
+ /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
+ /// </summary>
+ static class TextFormatterFactory
{
+ /// <summary>
+ /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
+ /// </summary>
+ public static TextFormatter Create(Control owner)
+ {
+ return TextFormatter.Current;
+ }
+
/// <summary>
/// Creates formatted text.
/// </summary>
@@ -40,41 +46,26 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
- {
- var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
- var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
-
- var textSource = new SimpleTextSource(text, defaultProperties);
-
- return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
- }
-
- private readonly struct SimpleTextSource : ITextSource
+ public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
- private readonly ReadOnlySlice<char> _text;
- private readonly TextRunProperties _defaultProperties;
-
- public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
- {
- _text = text;
- _defaultProperties = defaultProperties;
- }
-
- public TextRun GetTextRun(int textSourceIndex)
- {
- if (textSourceIndex < _text.Length)
- {
- return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
- }
-
- if (textSourceIndex > _text.Length)
- {
- return null;
- }
+ if (element == null)
+ throw new ArgumentNullException(nameof(element));
+ if (text == null)
+ throw new ArgumentNullException(nameof(text));
+ if (typeface == default)
+ typeface = element.CreateTypeface();
+ if (emSize == null)
+ emSize = TextBlock.GetFontSize(element);
+ if (foreground == null)
+ foreground = TextBlock.GetForeground(element);
- return new TextEndOfParagraph(1);
- }
+ return new FormattedText(
+ text,
+ CultureInfo.CurrentCulture,
+ FlowDirection.LeftToRight,
+ typeface,
+ emSize.Value,
+ foreground);
}
}
}
| 32 | Redo Avalonia port of AvalonEdit.Rendering | 41 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059852 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using Avalonia.Utilities;
using AvaloniaEdit.Rendering;
using TextLine = Avalonia.Media.TextFormatting.TextLine;
using TextRun = Avalonia.Media.TextFormatting.TextRun;
using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
public static class TextFormatterFactory
{
/// <summary>
/// Creates formatted text.
/// </summary>
/// </summary>
/// <param name="element">The owner element. The text formatter setting are read from this element.</param>
/// <param name="text">The text.</param>
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
{
var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
var textSource = new SimpleTextSource(text, defaultProperties);
return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
}
private readonly struct SimpleTextSource : ITextSource
{
private readonly ReadOnlySlice<char> _text;
private readonly TextRunProperties _defaultProperties;
public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
{
_text = text;
_defaultProperties = defaultProperties;
}
public TextRun GetTextRun(int textSourceIndex)
{
if (textSourceIndex < _text.Length)
{
return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
}
if (textSourceIndex > _text.Length)
{
return null;
}
return new TextEndOfParagraph(1);
}
}
}
}
}
<MSG> Redo Avalonia port of AvalonEdit.Rendering
<DFF> @@ -16,21 +16,27 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
+using System;
+using System.Globalization;
+using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
-using Avalonia.Utilities;
-using AvaloniaEdit.Rendering;
-using TextLine = Avalonia.Media.TextFormatting.TextLine;
-using TextRun = Avalonia.Media.TextFormatting.TextRun;
-using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
- /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
- /// </summary>
- public static class TextFormatterFactory
+ /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
+ /// </summary>
+ static class TextFormatterFactory
{
+ /// <summary>
+ /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
+ /// </summary>
+ public static TextFormatter Create(Control owner)
+ {
+ return TextFormatter.Current;
+ }
+
/// <summary>
/// Creates formatted text.
/// </summary>
@@ -40,41 +46,26 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
- {
- var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
- var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
-
- var textSource = new SimpleTextSource(text, defaultProperties);
-
- return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
- }
-
- private readonly struct SimpleTextSource : ITextSource
+ public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
- private readonly ReadOnlySlice<char> _text;
- private readonly TextRunProperties _defaultProperties;
-
- public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
- {
- _text = text;
- _defaultProperties = defaultProperties;
- }
-
- public TextRun GetTextRun(int textSourceIndex)
- {
- if (textSourceIndex < _text.Length)
- {
- return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
- }
-
- if (textSourceIndex > _text.Length)
- {
- return null;
- }
+ if (element == null)
+ throw new ArgumentNullException(nameof(element));
+ if (text == null)
+ throw new ArgumentNullException(nameof(text));
+ if (typeface == default)
+ typeface = element.CreateTypeface();
+ if (emSize == null)
+ emSize = TextBlock.GetFontSize(element);
+ if (foreground == null)
+ foreground = TextBlock.GetForeground(element);
- return new TextEndOfParagraph(1);
- }
+ return new FormattedText(
+ text,
+ CultureInfo.CurrentCulture,
+ FlowDirection.LeftToRight,
+ typeface,
+ emSize.Value,
+ foreground);
}
}
}
| 32 | Redo Avalonia port of AvalonEdit.Rendering | 41 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059853 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using Avalonia.Utilities;
using AvaloniaEdit.Rendering;
using TextLine = Avalonia.Media.TextFormatting.TextLine;
using TextRun = Avalonia.Media.TextFormatting.TextRun;
using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
public static class TextFormatterFactory
{
/// <summary>
/// Creates formatted text.
/// </summary>
/// </summary>
/// <param name="element">The owner element. The text formatter setting are read from this element.</param>
/// <param name="text">The text.</param>
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
{
var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
var textSource = new SimpleTextSource(text, defaultProperties);
return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
}
private readonly struct SimpleTextSource : ITextSource
{
private readonly ReadOnlySlice<char> _text;
private readonly TextRunProperties _defaultProperties;
public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
{
_text = text;
_defaultProperties = defaultProperties;
}
public TextRun GetTextRun(int textSourceIndex)
{
if (textSourceIndex < _text.Length)
{
return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
}
if (textSourceIndex > _text.Length)
{
return null;
}
return new TextEndOfParagraph(1);
}
}
}
}
}
<MSG> Redo Avalonia port of AvalonEdit.Rendering
<DFF> @@ -16,21 +16,27 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
+using System;
+using System.Globalization;
+using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
-using Avalonia.Utilities;
-using AvaloniaEdit.Rendering;
-using TextLine = Avalonia.Media.TextFormatting.TextLine;
-using TextRun = Avalonia.Media.TextFormatting.TextRun;
-using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
- /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
- /// </summary>
- public static class TextFormatterFactory
+ /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
+ /// </summary>
+ static class TextFormatterFactory
{
+ /// <summary>
+ /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
+ /// </summary>
+ public static TextFormatter Create(Control owner)
+ {
+ return TextFormatter.Current;
+ }
+
/// <summary>
/// Creates formatted text.
/// </summary>
@@ -40,41 +46,26 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
- {
- var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
- var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
-
- var textSource = new SimpleTextSource(text, defaultProperties);
-
- return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
- }
-
- private readonly struct SimpleTextSource : ITextSource
+ public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
- private readonly ReadOnlySlice<char> _text;
- private readonly TextRunProperties _defaultProperties;
-
- public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
- {
- _text = text;
- _defaultProperties = defaultProperties;
- }
-
- public TextRun GetTextRun(int textSourceIndex)
- {
- if (textSourceIndex < _text.Length)
- {
- return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
- }
-
- if (textSourceIndex > _text.Length)
- {
- return null;
- }
+ if (element == null)
+ throw new ArgumentNullException(nameof(element));
+ if (text == null)
+ throw new ArgumentNullException(nameof(text));
+ if (typeface == default)
+ typeface = element.CreateTypeface();
+ if (emSize == null)
+ emSize = TextBlock.GetFontSize(element);
+ if (foreground == null)
+ foreground = TextBlock.GetForeground(element);
- return new TextEndOfParagraph(1);
- }
+ return new FormattedText(
+ text,
+ CultureInfo.CurrentCulture,
+ FlowDirection.LeftToRight,
+ typeface,
+ emSize.Value,
+ foreground);
}
}
}
| 32 | Redo Avalonia port of AvalonEdit.Rendering | 41 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059854 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using Avalonia.Utilities;
using AvaloniaEdit.Rendering;
using TextLine = Avalonia.Media.TextFormatting.TextLine;
using TextRun = Avalonia.Media.TextFormatting.TextRun;
using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
public static class TextFormatterFactory
{
/// <summary>
/// Creates formatted text.
/// </summary>
/// </summary>
/// <param name="element">The owner element. The text formatter setting are read from this element.</param>
/// <param name="text">The text.</param>
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
{
var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
var textSource = new SimpleTextSource(text, defaultProperties);
return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
}
private readonly struct SimpleTextSource : ITextSource
{
private readonly ReadOnlySlice<char> _text;
private readonly TextRunProperties _defaultProperties;
public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
{
_text = text;
_defaultProperties = defaultProperties;
}
public TextRun GetTextRun(int textSourceIndex)
{
if (textSourceIndex < _text.Length)
{
return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
}
if (textSourceIndex > _text.Length)
{
return null;
}
return new TextEndOfParagraph(1);
}
}
}
}
}
<MSG> Redo Avalonia port of AvalonEdit.Rendering
<DFF> @@ -16,21 +16,27 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
+using System;
+using System.Globalization;
+using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
-using Avalonia.Utilities;
-using AvaloniaEdit.Rendering;
-using TextLine = Avalonia.Media.TextFormatting.TextLine;
-using TextRun = Avalonia.Media.TextFormatting.TextRun;
-using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
- /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
- /// </summary>
- public static class TextFormatterFactory
+ /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
+ /// </summary>
+ static class TextFormatterFactory
{
+ /// <summary>
+ /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
+ /// </summary>
+ public static TextFormatter Create(Control owner)
+ {
+ return TextFormatter.Current;
+ }
+
/// <summary>
/// Creates formatted text.
/// </summary>
@@ -40,41 +46,26 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
- {
- var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
- var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
-
- var textSource = new SimpleTextSource(text, defaultProperties);
-
- return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
- }
-
- private readonly struct SimpleTextSource : ITextSource
+ public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
- private readonly ReadOnlySlice<char> _text;
- private readonly TextRunProperties _defaultProperties;
-
- public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
- {
- _text = text;
- _defaultProperties = defaultProperties;
- }
-
- public TextRun GetTextRun(int textSourceIndex)
- {
- if (textSourceIndex < _text.Length)
- {
- return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
- }
-
- if (textSourceIndex > _text.Length)
- {
- return null;
- }
+ if (element == null)
+ throw new ArgumentNullException(nameof(element));
+ if (text == null)
+ throw new ArgumentNullException(nameof(text));
+ if (typeface == default)
+ typeface = element.CreateTypeface();
+ if (emSize == null)
+ emSize = TextBlock.GetFontSize(element);
+ if (foreground == null)
+ foreground = TextBlock.GetForeground(element);
- return new TextEndOfParagraph(1);
- }
+ return new FormattedText(
+ text,
+ CultureInfo.CurrentCulture,
+ FlowDirection.LeftToRight,
+ typeface,
+ emSize.Value,
+ foreground);
}
}
}
| 32 | Redo Avalonia port of AvalonEdit.Rendering | 41 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059855 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using Avalonia.Utilities;
using AvaloniaEdit.Rendering;
using TextLine = Avalonia.Media.TextFormatting.TextLine;
using TextRun = Avalonia.Media.TextFormatting.TextRun;
using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
public static class TextFormatterFactory
{
/// <summary>
/// Creates formatted text.
/// </summary>
/// </summary>
/// <param name="element">The owner element. The text formatter setting are read from this element.</param>
/// <param name="text">The text.</param>
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
{
var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
var textSource = new SimpleTextSource(text, defaultProperties);
return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
}
private readonly struct SimpleTextSource : ITextSource
{
private readonly ReadOnlySlice<char> _text;
private readonly TextRunProperties _defaultProperties;
public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
{
_text = text;
_defaultProperties = defaultProperties;
}
public TextRun GetTextRun(int textSourceIndex)
{
if (textSourceIndex < _text.Length)
{
return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
}
if (textSourceIndex > _text.Length)
{
return null;
}
return new TextEndOfParagraph(1);
}
}
}
}
}
<MSG> Redo Avalonia port of AvalonEdit.Rendering
<DFF> @@ -16,21 +16,27 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
+using System;
+using System.Globalization;
+using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
-using Avalonia.Utilities;
-using AvaloniaEdit.Rendering;
-using TextLine = Avalonia.Media.TextFormatting.TextLine;
-using TextRun = Avalonia.Media.TextFormatting.TextRun;
-using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
- /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
- /// </summary>
- public static class TextFormatterFactory
+ /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
+ /// </summary>
+ static class TextFormatterFactory
{
+ /// <summary>
+ /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
+ /// </summary>
+ public static TextFormatter Create(Control owner)
+ {
+ return TextFormatter.Current;
+ }
+
/// <summary>
/// Creates formatted text.
/// </summary>
@@ -40,41 +46,26 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
- {
- var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
- var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
-
- var textSource = new SimpleTextSource(text, defaultProperties);
-
- return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
- }
-
- private readonly struct SimpleTextSource : ITextSource
+ public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
- private readonly ReadOnlySlice<char> _text;
- private readonly TextRunProperties _defaultProperties;
-
- public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
- {
- _text = text;
- _defaultProperties = defaultProperties;
- }
-
- public TextRun GetTextRun(int textSourceIndex)
- {
- if (textSourceIndex < _text.Length)
- {
- return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
- }
-
- if (textSourceIndex > _text.Length)
- {
- return null;
- }
+ if (element == null)
+ throw new ArgumentNullException(nameof(element));
+ if (text == null)
+ throw new ArgumentNullException(nameof(text));
+ if (typeface == default)
+ typeface = element.CreateTypeface();
+ if (emSize == null)
+ emSize = TextBlock.GetFontSize(element);
+ if (foreground == null)
+ foreground = TextBlock.GetForeground(element);
- return new TextEndOfParagraph(1);
- }
+ return new FormattedText(
+ text,
+ CultureInfo.CurrentCulture,
+ FlowDirection.LeftToRight,
+ typeface,
+ emSize.Value,
+ foreground);
}
}
}
| 32 | Redo Avalonia port of AvalonEdit.Rendering | 41 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059856 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using Avalonia.Utilities;
using AvaloniaEdit.Rendering;
using TextLine = Avalonia.Media.TextFormatting.TextLine;
using TextRun = Avalonia.Media.TextFormatting.TextRun;
using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
public static class TextFormatterFactory
{
/// <summary>
/// Creates formatted text.
/// </summary>
/// </summary>
/// <param name="element">The owner element. The text formatter setting are read from this element.</param>
/// <param name="text">The text.</param>
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
{
var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
var textSource = new SimpleTextSource(text, defaultProperties);
return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
}
private readonly struct SimpleTextSource : ITextSource
{
private readonly ReadOnlySlice<char> _text;
private readonly TextRunProperties _defaultProperties;
public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
{
_text = text;
_defaultProperties = defaultProperties;
}
public TextRun GetTextRun(int textSourceIndex)
{
if (textSourceIndex < _text.Length)
{
return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
}
if (textSourceIndex > _text.Length)
{
return null;
}
return new TextEndOfParagraph(1);
}
}
}
}
}
<MSG> Redo Avalonia port of AvalonEdit.Rendering
<DFF> @@ -16,21 +16,27 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
+using System;
+using System.Globalization;
+using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
-using Avalonia.Utilities;
-using AvaloniaEdit.Rendering;
-using TextLine = Avalonia.Media.TextFormatting.TextLine;
-using TextRun = Avalonia.Media.TextFormatting.TextRun;
-using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
- /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
- /// </summary>
- public static class TextFormatterFactory
+ /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
+ /// </summary>
+ static class TextFormatterFactory
{
+ /// <summary>
+ /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
+ /// </summary>
+ public static TextFormatter Create(Control owner)
+ {
+ return TextFormatter.Current;
+ }
+
/// <summary>
/// Creates formatted text.
/// </summary>
@@ -40,41 +46,26 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
- {
- var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
- var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
-
- var textSource = new SimpleTextSource(text, defaultProperties);
-
- return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
- }
-
- private readonly struct SimpleTextSource : ITextSource
+ public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
- private readonly ReadOnlySlice<char> _text;
- private readonly TextRunProperties _defaultProperties;
-
- public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
- {
- _text = text;
- _defaultProperties = defaultProperties;
- }
-
- public TextRun GetTextRun(int textSourceIndex)
- {
- if (textSourceIndex < _text.Length)
- {
- return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
- }
-
- if (textSourceIndex > _text.Length)
- {
- return null;
- }
+ if (element == null)
+ throw new ArgumentNullException(nameof(element));
+ if (text == null)
+ throw new ArgumentNullException(nameof(text));
+ if (typeface == default)
+ typeface = element.CreateTypeface();
+ if (emSize == null)
+ emSize = TextBlock.GetFontSize(element);
+ if (foreground == null)
+ foreground = TextBlock.GetForeground(element);
- return new TextEndOfParagraph(1);
- }
+ return new FormattedText(
+ text,
+ CultureInfo.CurrentCulture,
+ FlowDirection.LeftToRight,
+ typeface,
+ emSize.Value,
+ foreground);
}
}
}
| 32 | Redo Avalonia port of AvalonEdit.Rendering | 41 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059857 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using Avalonia.Utilities;
using AvaloniaEdit.Rendering;
using TextLine = Avalonia.Media.TextFormatting.TextLine;
using TextRun = Avalonia.Media.TextFormatting.TextRun;
using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
public static class TextFormatterFactory
{
/// <summary>
/// Creates formatted text.
/// </summary>
/// </summary>
/// <param name="element">The owner element. The text formatter setting are read from this element.</param>
/// <param name="text">The text.</param>
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
{
var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
var textSource = new SimpleTextSource(text, defaultProperties);
return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
}
private readonly struct SimpleTextSource : ITextSource
{
private readonly ReadOnlySlice<char> _text;
private readonly TextRunProperties _defaultProperties;
public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
{
_text = text;
_defaultProperties = defaultProperties;
}
public TextRun GetTextRun(int textSourceIndex)
{
if (textSourceIndex < _text.Length)
{
return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
}
if (textSourceIndex > _text.Length)
{
return null;
}
return new TextEndOfParagraph(1);
}
}
}
}
}
<MSG> Redo Avalonia port of AvalonEdit.Rendering
<DFF> @@ -16,21 +16,27 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
+using System;
+using System.Globalization;
+using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
-using Avalonia.Utilities;
-using AvaloniaEdit.Rendering;
-using TextLine = Avalonia.Media.TextFormatting.TextLine;
-using TextRun = Avalonia.Media.TextFormatting.TextRun;
-using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
- /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
- /// </summary>
- public static class TextFormatterFactory
+ /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
+ /// </summary>
+ static class TextFormatterFactory
{
+ /// <summary>
+ /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
+ /// </summary>
+ public static TextFormatter Create(Control owner)
+ {
+ return TextFormatter.Current;
+ }
+
/// <summary>
/// Creates formatted text.
/// </summary>
@@ -40,41 +46,26 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
- {
- var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
- var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
-
- var textSource = new SimpleTextSource(text, defaultProperties);
-
- return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
- }
-
- private readonly struct SimpleTextSource : ITextSource
+ public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
- private readonly ReadOnlySlice<char> _text;
- private readonly TextRunProperties _defaultProperties;
-
- public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
- {
- _text = text;
- _defaultProperties = defaultProperties;
- }
-
- public TextRun GetTextRun(int textSourceIndex)
- {
- if (textSourceIndex < _text.Length)
- {
- return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
- }
-
- if (textSourceIndex > _text.Length)
- {
- return null;
- }
+ if (element == null)
+ throw new ArgumentNullException(nameof(element));
+ if (text == null)
+ throw new ArgumentNullException(nameof(text));
+ if (typeface == default)
+ typeface = element.CreateTypeface();
+ if (emSize == null)
+ emSize = TextBlock.GetFontSize(element);
+ if (foreground == null)
+ foreground = TextBlock.GetForeground(element);
- return new TextEndOfParagraph(1);
- }
+ return new FormattedText(
+ text,
+ CultureInfo.CurrentCulture,
+ FlowDirection.LeftToRight,
+ typeface,
+ emSize.Value,
+ foreground);
}
}
}
| 32 | Redo Avalonia port of AvalonEdit.Rendering | 41 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059858 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using Avalonia.Utilities;
using AvaloniaEdit.Rendering;
using TextLine = Avalonia.Media.TextFormatting.TextLine;
using TextRun = Avalonia.Media.TextFormatting.TextRun;
using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
public static class TextFormatterFactory
{
/// <summary>
/// Creates formatted text.
/// </summary>
/// </summary>
/// <param name="element">The owner element. The text formatter setting are read from this element.</param>
/// <param name="text">The text.</param>
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
{
var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
var textSource = new SimpleTextSource(text, defaultProperties);
return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
}
private readonly struct SimpleTextSource : ITextSource
{
private readonly ReadOnlySlice<char> _text;
private readonly TextRunProperties _defaultProperties;
public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
{
_text = text;
_defaultProperties = defaultProperties;
}
public TextRun GetTextRun(int textSourceIndex)
{
if (textSourceIndex < _text.Length)
{
return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
}
if (textSourceIndex > _text.Length)
{
return null;
}
return new TextEndOfParagraph(1);
}
}
}
}
}
<MSG> Redo Avalonia port of AvalonEdit.Rendering
<DFF> @@ -16,21 +16,27 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
+using System;
+using System.Globalization;
+using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
-using Avalonia.Utilities;
-using AvaloniaEdit.Rendering;
-using TextLine = Avalonia.Media.TextFormatting.TextLine;
-using TextRun = Avalonia.Media.TextFormatting.TextRun;
-using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
- /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
- /// </summary>
- public static class TextFormatterFactory
+ /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
+ /// </summary>
+ static class TextFormatterFactory
{
+ /// <summary>
+ /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
+ /// </summary>
+ public static TextFormatter Create(Control owner)
+ {
+ return TextFormatter.Current;
+ }
+
/// <summary>
/// Creates formatted text.
/// </summary>
@@ -40,41 +46,26 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
- {
- var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
- var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
-
- var textSource = new SimpleTextSource(text, defaultProperties);
-
- return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
- }
-
- private readonly struct SimpleTextSource : ITextSource
+ public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
- private readonly ReadOnlySlice<char> _text;
- private readonly TextRunProperties _defaultProperties;
-
- public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
- {
- _text = text;
- _defaultProperties = defaultProperties;
- }
-
- public TextRun GetTextRun(int textSourceIndex)
- {
- if (textSourceIndex < _text.Length)
- {
- return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
- }
-
- if (textSourceIndex > _text.Length)
- {
- return null;
- }
+ if (element == null)
+ throw new ArgumentNullException(nameof(element));
+ if (text == null)
+ throw new ArgumentNullException(nameof(text));
+ if (typeface == default)
+ typeface = element.CreateTypeface();
+ if (emSize == null)
+ emSize = TextBlock.GetFontSize(element);
+ if (foreground == null)
+ foreground = TextBlock.GetForeground(element);
- return new TextEndOfParagraph(1);
- }
+ return new FormattedText(
+ text,
+ CultureInfo.CurrentCulture,
+ FlowDirection.LeftToRight,
+ typeface,
+ emSize.Value,
+ foreground);
}
}
}
| 32 | Redo Avalonia port of AvalonEdit.Rendering | 41 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059859 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using Avalonia.Utilities;
using AvaloniaEdit.Rendering;
using TextLine = Avalonia.Media.TextFormatting.TextLine;
using TextRun = Avalonia.Media.TextFormatting.TextRun;
using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
public static class TextFormatterFactory
{
/// <summary>
/// Creates formatted text.
/// </summary>
/// </summary>
/// <param name="element">The owner element. The text formatter setting are read from this element.</param>
/// <param name="text">The text.</param>
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
{
var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
var textSource = new SimpleTextSource(text, defaultProperties);
return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
}
private readonly struct SimpleTextSource : ITextSource
{
private readonly ReadOnlySlice<char> _text;
private readonly TextRunProperties _defaultProperties;
public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
{
_text = text;
_defaultProperties = defaultProperties;
}
public TextRun GetTextRun(int textSourceIndex)
{
if (textSourceIndex < _text.Length)
{
return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
}
if (textSourceIndex > _text.Length)
{
return null;
}
return new TextEndOfParagraph(1);
}
}
}
}
}
<MSG> Redo Avalonia port of AvalonEdit.Rendering
<DFF> @@ -16,21 +16,27 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
+using System;
+using System.Globalization;
+using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
-using Avalonia.Utilities;
-using AvaloniaEdit.Rendering;
-using TextLine = Avalonia.Media.TextFormatting.TextLine;
-using TextRun = Avalonia.Media.TextFormatting.TextRun;
-using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
- /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
- /// </summary>
- public static class TextFormatterFactory
+ /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
+ /// </summary>
+ static class TextFormatterFactory
{
+ /// <summary>
+ /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
+ /// </summary>
+ public static TextFormatter Create(Control owner)
+ {
+ return TextFormatter.Current;
+ }
+
/// <summary>
/// Creates formatted text.
/// </summary>
@@ -40,41 +46,26 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
- {
- var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
- var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
-
- var textSource = new SimpleTextSource(text, defaultProperties);
-
- return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
- }
-
- private readonly struct SimpleTextSource : ITextSource
+ public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
- private readonly ReadOnlySlice<char> _text;
- private readonly TextRunProperties _defaultProperties;
-
- public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
- {
- _text = text;
- _defaultProperties = defaultProperties;
- }
-
- public TextRun GetTextRun(int textSourceIndex)
- {
- if (textSourceIndex < _text.Length)
- {
- return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
- }
-
- if (textSourceIndex > _text.Length)
- {
- return null;
- }
+ if (element == null)
+ throw new ArgumentNullException(nameof(element));
+ if (text == null)
+ throw new ArgumentNullException(nameof(text));
+ if (typeface == default)
+ typeface = element.CreateTypeface();
+ if (emSize == null)
+ emSize = TextBlock.GetFontSize(element);
+ if (foreground == null)
+ foreground = TextBlock.GetForeground(element);
- return new TextEndOfParagraph(1);
- }
+ return new FormattedText(
+ text,
+ CultureInfo.CurrentCulture,
+ FlowDirection.LeftToRight,
+ typeface,
+ emSize.Value,
+ foreground);
}
}
}
| 32 | Redo Avalonia port of AvalonEdit.Rendering | 41 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059860 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using Avalonia.Utilities;
using AvaloniaEdit.Rendering;
using TextLine = Avalonia.Media.TextFormatting.TextLine;
using TextRun = Avalonia.Media.TextFormatting.TextRun;
using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
public static class TextFormatterFactory
{
/// <summary>
/// Creates formatted text.
/// </summary>
/// </summary>
/// <param name="element">The owner element. The text formatter setting are read from this element.</param>
/// <param name="text">The text.</param>
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
{
var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
var textSource = new SimpleTextSource(text, defaultProperties);
return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
}
private readonly struct SimpleTextSource : ITextSource
{
private readonly ReadOnlySlice<char> _text;
private readonly TextRunProperties _defaultProperties;
public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
{
_text = text;
_defaultProperties = defaultProperties;
}
public TextRun GetTextRun(int textSourceIndex)
{
if (textSourceIndex < _text.Length)
{
return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
}
if (textSourceIndex > _text.Length)
{
return null;
}
return new TextEndOfParagraph(1);
}
}
}
}
}
<MSG> Redo Avalonia port of AvalonEdit.Rendering
<DFF> @@ -16,21 +16,27 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
+using System;
+using System.Globalization;
+using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
-using Avalonia.Utilities;
-using AvaloniaEdit.Rendering;
-using TextLine = Avalonia.Media.TextFormatting.TextLine;
-using TextRun = Avalonia.Media.TextFormatting.TextRun;
-using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
- /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
- /// </summary>
- public static class TextFormatterFactory
+ /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
+ /// </summary>
+ static class TextFormatterFactory
{
+ /// <summary>
+ /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
+ /// </summary>
+ public static TextFormatter Create(Control owner)
+ {
+ return TextFormatter.Current;
+ }
+
/// <summary>
/// Creates formatted text.
/// </summary>
@@ -40,41 +46,26 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
- {
- var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
- var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
-
- var textSource = new SimpleTextSource(text, defaultProperties);
-
- return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
- }
-
- private readonly struct SimpleTextSource : ITextSource
+ public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
- private readonly ReadOnlySlice<char> _text;
- private readonly TextRunProperties _defaultProperties;
-
- public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
- {
- _text = text;
- _defaultProperties = defaultProperties;
- }
-
- public TextRun GetTextRun(int textSourceIndex)
- {
- if (textSourceIndex < _text.Length)
- {
- return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
- }
-
- if (textSourceIndex > _text.Length)
- {
- return null;
- }
+ if (element == null)
+ throw new ArgumentNullException(nameof(element));
+ if (text == null)
+ throw new ArgumentNullException(nameof(text));
+ if (typeface == default)
+ typeface = element.CreateTypeface();
+ if (emSize == null)
+ emSize = TextBlock.GetFontSize(element);
+ if (foreground == null)
+ foreground = TextBlock.GetForeground(element);
- return new TextEndOfParagraph(1);
- }
+ return new FormattedText(
+ text,
+ CultureInfo.CurrentCulture,
+ FlowDirection.LeftToRight,
+ typeface,
+ emSize.Value,
+ foreground);
}
}
}
| 32 | Redo Avalonia port of AvalonEdit.Rendering | 41 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059861 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using Avalonia.Utilities;
using AvaloniaEdit.Rendering;
using TextLine = Avalonia.Media.TextFormatting.TextLine;
using TextRun = Avalonia.Media.TextFormatting.TextRun;
using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
public static class TextFormatterFactory
{
/// <summary>
/// Creates formatted text.
/// </summary>
/// </summary>
/// <param name="element">The owner element. The text formatter setting are read from this element.</param>
/// <param name="text">The text.</param>
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
{
var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
var textSource = new SimpleTextSource(text, defaultProperties);
return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
}
private readonly struct SimpleTextSource : ITextSource
{
private readonly ReadOnlySlice<char> _text;
private readonly TextRunProperties _defaultProperties;
public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
{
_text = text;
_defaultProperties = defaultProperties;
}
public TextRun GetTextRun(int textSourceIndex)
{
if (textSourceIndex < _text.Length)
{
return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
}
if (textSourceIndex > _text.Length)
{
return null;
}
return new TextEndOfParagraph(1);
}
}
}
}
}
<MSG> Redo Avalonia port of AvalonEdit.Rendering
<DFF> @@ -16,21 +16,27 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
+using System;
+using System.Globalization;
+using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
-using Avalonia.Utilities;
-using AvaloniaEdit.Rendering;
-using TextLine = Avalonia.Media.TextFormatting.TextLine;
-using TextRun = Avalonia.Media.TextFormatting.TextRun;
-using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
- /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
- /// </summary>
- public static class TextFormatterFactory
+ /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
+ /// </summary>
+ static class TextFormatterFactory
{
+ /// <summary>
+ /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
+ /// </summary>
+ public static TextFormatter Create(Control owner)
+ {
+ return TextFormatter.Current;
+ }
+
/// <summary>
/// Creates formatted text.
/// </summary>
@@ -40,41 +46,26 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
- {
- var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
- var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
-
- var textSource = new SimpleTextSource(text, defaultProperties);
-
- return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
- }
-
- private readonly struct SimpleTextSource : ITextSource
+ public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
- private readonly ReadOnlySlice<char> _text;
- private readonly TextRunProperties _defaultProperties;
-
- public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
- {
- _text = text;
- _defaultProperties = defaultProperties;
- }
-
- public TextRun GetTextRun(int textSourceIndex)
- {
- if (textSourceIndex < _text.Length)
- {
- return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
- }
-
- if (textSourceIndex > _text.Length)
- {
- return null;
- }
+ if (element == null)
+ throw new ArgumentNullException(nameof(element));
+ if (text == null)
+ throw new ArgumentNullException(nameof(text));
+ if (typeface == default)
+ typeface = element.CreateTypeface();
+ if (emSize == null)
+ emSize = TextBlock.GetFontSize(element);
+ if (foreground == null)
+ foreground = TextBlock.GetForeground(element);
- return new TextEndOfParagraph(1);
- }
+ return new FormattedText(
+ text,
+ CultureInfo.CurrentCulture,
+ FlowDirection.LeftToRight,
+ typeface,
+ emSize.Value,
+ foreground);
}
}
}
| 32 | Redo Avalonia port of AvalonEdit.Rendering | 41 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059862 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using Avalonia.Utilities;
using AvaloniaEdit.Rendering;
using TextLine = Avalonia.Media.TextFormatting.TextLine;
using TextRun = Avalonia.Media.TextFormatting.TextRun;
using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
public static class TextFormatterFactory
{
/// <summary>
/// Creates formatted text.
/// </summary>
/// </summary>
/// <param name="element">The owner element. The text formatter setting are read from this element.</param>
/// <param name="text">The text.</param>
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
{
var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
var textSource = new SimpleTextSource(text, defaultProperties);
return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
}
private readonly struct SimpleTextSource : ITextSource
{
private readonly ReadOnlySlice<char> _text;
private readonly TextRunProperties _defaultProperties;
public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
{
_text = text;
_defaultProperties = defaultProperties;
}
public TextRun GetTextRun(int textSourceIndex)
{
if (textSourceIndex < _text.Length)
{
return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
}
if (textSourceIndex > _text.Length)
{
return null;
}
return new TextEndOfParagraph(1);
}
}
}
}
}
<MSG> Redo Avalonia port of AvalonEdit.Rendering
<DFF> @@ -16,21 +16,27 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
+using System;
+using System.Globalization;
+using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
-using Avalonia.Utilities;
-using AvaloniaEdit.Rendering;
-using TextLine = Avalonia.Media.TextFormatting.TextLine;
-using TextRun = Avalonia.Media.TextFormatting.TextRun;
-using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
- /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
- /// </summary>
- public static class TextFormatterFactory
+ /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
+ /// </summary>
+ static class TextFormatterFactory
{
+ /// <summary>
+ /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
+ /// </summary>
+ public static TextFormatter Create(Control owner)
+ {
+ return TextFormatter.Current;
+ }
+
/// <summary>
/// Creates formatted text.
/// </summary>
@@ -40,41 +46,26 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
- {
- var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
- var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
-
- var textSource = new SimpleTextSource(text, defaultProperties);
-
- return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
- }
-
- private readonly struct SimpleTextSource : ITextSource
+ public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
- private readonly ReadOnlySlice<char> _text;
- private readonly TextRunProperties _defaultProperties;
-
- public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
- {
- _text = text;
- _defaultProperties = defaultProperties;
- }
-
- public TextRun GetTextRun(int textSourceIndex)
- {
- if (textSourceIndex < _text.Length)
- {
- return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
- }
-
- if (textSourceIndex > _text.Length)
- {
- return null;
- }
+ if (element == null)
+ throw new ArgumentNullException(nameof(element));
+ if (text == null)
+ throw new ArgumentNullException(nameof(text));
+ if (typeface == default)
+ typeface = element.CreateTypeface();
+ if (emSize == null)
+ emSize = TextBlock.GetFontSize(element);
+ if (foreground == null)
+ foreground = TextBlock.GetForeground(element);
- return new TextEndOfParagraph(1);
- }
+ return new FormattedText(
+ text,
+ CultureInfo.CurrentCulture,
+ FlowDirection.LeftToRight,
+ typeface,
+ emSize.Value,
+ foreground);
}
}
}
| 32 | Redo Avalonia port of AvalonEdit.Rendering | 41 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059863 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using Avalonia.Utilities;
using AvaloniaEdit.Rendering;
using TextLine = Avalonia.Media.TextFormatting.TextLine;
using TextRun = Avalonia.Media.TextFormatting.TextRun;
using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
public static class TextFormatterFactory
{
/// <summary>
/// Creates formatted text.
/// </summary>
/// </summary>
/// <param name="element">The owner element. The text formatter setting are read from this element.</param>
/// <param name="text">The text.</param>
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
{
var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
var textSource = new SimpleTextSource(text, defaultProperties);
return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
}
private readonly struct SimpleTextSource : ITextSource
{
private readonly ReadOnlySlice<char> _text;
private readonly TextRunProperties _defaultProperties;
public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
{
_text = text;
_defaultProperties = defaultProperties;
}
public TextRun GetTextRun(int textSourceIndex)
{
if (textSourceIndex < _text.Length)
{
return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
}
if (textSourceIndex > _text.Length)
{
return null;
}
return new TextEndOfParagraph(1);
}
}
}
}
}
<MSG> Redo Avalonia port of AvalonEdit.Rendering
<DFF> @@ -16,21 +16,27 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
+using System;
+using System.Globalization;
+using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
-using Avalonia.Utilities;
-using AvaloniaEdit.Rendering;
-using TextLine = Avalonia.Media.TextFormatting.TextLine;
-using TextRun = Avalonia.Media.TextFormatting.TextRun;
-using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
- /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
- /// </summary>
- public static class TextFormatterFactory
+ /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
+ /// </summary>
+ static class TextFormatterFactory
{
+ /// <summary>
+ /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
+ /// </summary>
+ public static TextFormatter Create(Control owner)
+ {
+ return TextFormatter.Current;
+ }
+
/// <summary>
/// Creates formatted text.
/// </summary>
@@ -40,41 +46,26 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
- {
- var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
- var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
-
- var textSource = new SimpleTextSource(text, defaultProperties);
-
- return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
- }
-
- private readonly struct SimpleTextSource : ITextSource
+ public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
- private readonly ReadOnlySlice<char> _text;
- private readonly TextRunProperties _defaultProperties;
-
- public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
- {
- _text = text;
- _defaultProperties = defaultProperties;
- }
-
- public TextRun GetTextRun(int textSourceIndex)
- {
- if (textSourceIndex < _text.Length)
- {
- return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
- }
-
- if (textSourceIndex > _text.Length)
- {
- return null;
- }
+ if (element == null)
+ throw new ArgumentNullException(nameof(element));
+ if (text == null)
+ throw new ArgumentNullException(nameof(text));
+ if (typeface == default)
+ typeface = element.CreateTypeface();
+ if (emSize == null)
+ emSize = TextBlock.GetFontSize(element);
+ if (foreground == null)
+ foreground = TextBlock.GetForeground(element);
- return new TextEndOfParagraph(1);
- }
+ return new FormattedText(
+ text,
+ CultureInfo.CurrentCulture,
+ FlowDirection.LeftToRight,
+ typeface,
+ emSize.Value,
+ foreground);
}
}
}
| 32 | Redo Avalonia port of AvalonEdit.Rendering | 41 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059864 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using Avalonia.Utilities;
using AvaloniaEdit.Rendering;
using TextLine = Avalonia.Media.TextFormatting.TextLine;
using TextRun = Avalonia.Media.TextFormatting.TextRun;
using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
public static class TextFormatterFactory
{
/// <summary>
/// Creates formatted text.
/// </summary>
/// </summary>
/// <param name="element">The owner element. The text formatter setting are read from this element.</param>
/// <param name="text">The text.</param>
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
{
var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
var textSource = new SimpleTextSource(text, defaultProperties);
return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
}
private readonly struct SimpleTextSource : ITextSource
{
private readonly ReadOnlySlice<char> _text;
private readonly TextRunProperties _defaultProperties;
public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
{
_text = text;
_defaultProperties = defaultProperties;
}
public TextRun GetTextRun(int textSourceIndex)
{
if (textSourceIndex < _text.Length)
{
return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
}
if (textSourceIndex > _text.Length)
{
return null;
}
return new TextEndOfParagraph(1);
}
}
}
}
}
<MSG> Redo Avalonia port of AvalonEdit.Rendering
<DFF> @@ -16,21 +16,27 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
+using System;
+using System.Globalization;
+using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
-using Avalonia.Utilities;
-using AvaloniaEdit.Rendering;
-using TextLine = Avalonia.Media.TextFormatting.TextLine;
-using TextRun = Avalonia.Media.TextFormatting.TextRun;
-using TextRunProperties = Avalonia.Media.TextFormatting.TextRunProperties;
namespace AvaloniaEdit.Utils
{
/// <summary>
- /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
- /// </summary>
- public static class TextFormatterFactory
+ /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
+ /// </summary>
+ static class TextFormatterFactory
{
+ /// <summary>
+ /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
+ /// </summary>
+ public static TextFormatter Create(Control owner)
+ {
+ return TextFormatter.Current;
+ }
+
/// <summary>
/// Creates formatted text.
/// </summary>
@@ -40,41 +46,26 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static TextLine FormatLine(ReadOnlySlice<char> text, Typeface typeface, double emSize, IBrush foreground)
- {
- var defaultProperties = new CustomTextRunProperties(typeface, emSize, null, foreground);
- var paragraphProperties = new CustomTextParagraphProperties(defaultProperties);
-
- var textSource = new SimpleTextSource(text, defaultProperties);
-
- return TextFormatter.Current.FormatLine(textSource, 0, double.PositiveInfinity, paragraphProperties);
- }
-
- private readonly struct SimpleTextSource : ITextSource
+ public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
- private readonly ReadOnlySlice<char> _text;
- private readonly TextRunProperties _defaultProperties;
-
- public SimpleTextSource(ReadOnlySlice<char> text, TextRunProperties defaultProperties)
- {
- _text = text;
- _defaultProperties = defaultProperties;
- }
-
- public TextRun GetTextRun(int textSourceIndex)
- {
- if (textSourceIndex < _text.Length)
- {
- return new TextCharacters(_text, textSourceIndex, _text.Length - textSourceIndex, _defaultProperties);
- }
-
- if (textSourceIndex > _text.Length)
- {
- return null;
- }
+ if (element == null)
+ throw new ArgumentNullException(nameof(element));
+ if (text == null)
+ throw new ArgumentNullException(nameof(text));
+ if (typeface == default)
+ typeface = element.CreateTypeface();
+ if (emSize == null)
+ emSize = TextBlock.GetFontSize(element);
+ if (foreground == null)
+ foreground = TextBlock.GetForeground(element);
- return new TextEndOfParagraph(1);
- }
+ return new FormattedText(
+ text,
+ CultureInfo.CurrentCulture,
+ FlowDirection.LeftToRight,
+ typeface,
+ emSize.Value,
+ foreground);
}
}
}
| 32 | Redo Avalonia port of AvalonEdit.Rendering | 41 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059865 | <NME> define.js
<BEF>
/*jslint browser:true, node:true, laxbreak:true*/
'use strict';
/**
* Creates and registers a
* FruitMachine view constructor
* and stores an internal reference.
*
* The user is able to pass in an already
* defined View constructor, or an object
* representing the View's prototype.
*
* @param {Object|View}
* @return {View}
*/
module.exports = function(fm) {
return function(props) {
var view = ('object' === typeof props)
? fm.View.extend(props)
: props;
var module = view.prototype._module;
// Store the module by module type
// so that module can be referred to
// by just a string in layout definitions
if (module) fm.modules[module] = view;
return view;
};
};
<MSG> Allowed for name to be used as an alternative to module in definition. Updated docs to reflect this.
<DFF> @@ -3,31 +3,42 @@
'use strict';
-/**
- * Creates and registers a
- * FruitMachine view constructor
- * and stores an internal reference.
- *
- * The user is able to pass in an already
- * defined View constructor, or an object
- * representing the View's prototype.
- *
- * @param {Object|View}
- * @return {View}
- */
module.exports = function(fm) {
+
+ /**
+ * Defines a module.
+ *
+ * Options:
+ *
+ * - `name {String}` the name of the module
+ * - `tag {String}` the tagName to use for the root element
+ * - `classes {Array}` a list of classes to add to the root element
+ * - `template {Function}` the template function to use when rendering
+ * - `helpers {Array}` a lsit of helpers to apply to the module
+ * - `initialize {Function}` custom logic to run when module instance created
+ * - `setup {Function}` custom logic to run when `.setup()` is called (directly or indirectly)
+ * - `teardown {Function}` custom logic to unbind/undo anything setup introduced (called on `.destroy()` and sometimes on `.setup()` to avoid double binding events)
+ * - `destroy {Function}` logic to permanently destroy all references
+ *
+ * @param {Object|View} props
+ * @return {View}
+ * @public true
+ */
return function(props) {
- var view = ('object' === typeof props)
+ var Module = ('object' === typeof props)
? fm.View.extend(props)
: props;
- var module = view.prototype._module;
+ // Allow modules to be named
+ // via 'name:' or 'module:'
+ var proto = Module.prototype;
+ var name = proto.name || proto._module;
// Store the module by module type
// so that module can be referred to
// by just a string in layout definitions
- if (module) fm.modules[module] = view;
+ if (name) fm.modules[name] = Module;
- return view;
+ return Module;
};
};
| 27 | Allowed for name to be used as an alternative to module in definition. Updated docs to reflect this. | 16 | .js | js | mit | ftlabs/fruitmachine |
10059866 | <NME> jsgrid.field.tests.js
<BEF> $(function() {
var Grid = jsGrid.Grid;
module("common field config", {
setup: function() {
this.isFieldExcluded = function(FieldClass) {
return FieldClass === jsGrid.ControlField;
};
}
});
test("filtering=false prevents rendering filter template", function() {
var isFieldExcluded = this.isFieldExcluded;
$.each(jsGrid.fields, function(name, FieldClass) {
if(isFieldExcluded(FieldClass))
return;
var field = new FieldClass({ filtering: false });
equal(field.filterTemplate(), "", "empty filter template for field " + name);
});
});
test("inserting=false prevents rendering insert template", function() {
var isFieldExcluded = this.isFieldExcluded;
$.each(jsGrid.fields, function(name, FieldClass) {
if(isFieldExcluded(FieldClass))
return;
var field = new FieldClass({ inserting: false });
equal(field.insertTemplate(), "", "empty insert template for field " + name);
});
});
test("editing=false renders itemTemplate", function() {
var isFieldExcluded = this.isFieldExcluded;
$.each(jsGrid.fields, function(name, FieldClass) {
if(isFieldExcluded(FieldClass))
return;
var item = {
field: "test"
};
var args;
var editTemplateContent = editTemplate instanceof jQuery ? editTemplate[0].outerHTML : editTemplate;
var itemTemplateContent = itemTemplate instanceof jQuery ? itemTemplate[0].outerHTML : itemTemplate;
console.log(name + ": " + editTemplateContent);
equal(editTemplateContent, itemTemplateContent, "item template is rendered instead of edit template for field " + name);
});
});
});
var itemTemplate = field.itemTemplate("test", item);
var editTemplate = field.editTemplate("test", item);
var editTemplateContent = editTemplate instanceof jQuery ? editTemplate[0].outerHTML : editTemplate;
var itemTemplateContent = itemTemplate instanceof jQuery ? itemTemplate[0].outerHTML : itemTemplate;
equal(editTemplateContent, itemTemplateContent, "item template is rendered instead of edit template for " + name);
equal(args.length, 2, "passed both arguments for " + name);
equal(args[0], "test", "field value passed as a first argument for " + name);
equal(args[1], item, "item passed as a second argument for " + name);
});
});
module("jsGrid.field");
test("basic", function() {
var customSortingFunc = function() {
return 1;
},
field = new jsGrid.Field({
name: "testField",
title: "testTitle",
sorter: customSortingFunc
});
equal(field.headerTemplate(), "testTitle");
equal(field.itemTemplate("testValue"), "testValue");
equal(field.filterTemplate(), "");
equal(field.insertTemplate(), "");
equal(field.editTemplate("testValue"), "testValue");
strictEqual(field.filterValue(), "");
strictEqual(field.insertValue(), "");
strictEqual(field.editValue(), "testValue");
strictEqual(field.sortingFunc, customSortingFunc);
});
module("jsGrid.field.text");
test("basic", function() {
var field = new jsGrid.TextField({ name: "testField" });
equal(field.itemTemplate("testValue"), "testValue");
equal(field.filterTemplate()[0].tagName.toLowerCase(), "input");
equal(field.insertTemplate()[0].tagName.toLowerCase(), "input");
equal(field.editTemplate("testEditValue")[0].tagName.toLowerCase(), "input");
strictEqual(field.filterValue(), "");
strictEqual(field.insertValue(), "");
strictEqual(field.editValue(), "testEditValue");
});
test("set default field options with setDefaults", function() {
jsGrid.setDefaults("text", {
defaultOption: "test"
});
var $element = $("#jsGrid").jsGrid({
fields: [{ type: "text" }]
});
equal($element.jsGrid("option", "fields")[0].defaultOption, "test", "default field option set");
});
module("jsGrid.field.number");
test("basic", function() {
var field = new jsGrid.NumberField({ name: "testField" });
equal(field.itemTemplate(5), "5");
equal(field.filterTemplate()[0].tagName.toLowerCase(), "input");
equal(field.insertTemplate()[0].tagName.toLowerCase(), "input");
equal(field.editTemplate(6)[0].tagName.toLowerCase(), "input");
strictEqual(field.filterValue(), undefined);
strictEqual(field.insertValue(), undefined);
strictEqual(field.editValue(), 6);
});
module("jsGrid.field.textArea");
test("basic", function() {
var field = new jsGrid.TextAreaField({ name: "testField" });
equal(field.itemTemplate("testValue"), "testValue");
equal(field.filterTemplate()[0].tagName.toLowerCase(), "input");
equal(field.insertTemplate()[0].tagName.toLowerCase(), "textarea");
equal(field.editTemplate("testEditValue")[0].tagName.toLowerCase(), "textarea");
strictEqual(field.insertValue(), "");
strictEqual(field.editValue(), "testEditValue");
});
module("jsGrid.field.checkbox");
test("basic", function() {
var field = new jsGrid.CheckboxField({ name: "testField" }),
itemTemplate,
filterTemplate,
insertTemplate,
editTemplate;
itemTemplate = field.itemTemplate("testValue");
equal(itemTemplate[0].tagName.toLowerCase(), "input");
equal(itemTemplate.attr("type"), "checkbox");
equal(itemTemplate.attr("disabled"), "disabled");
filterTemplate = field.filterTemplate();
equal(filterTemplate[0].tagName.toLowerCase(), "input");
equal(filterTemplate.attr("type"), "checkbox");
equal(filterTemplate.prop("indeterminate"), true);
insertTemplate = field.insertTemplate();
equal(insertTemplate[0].tagName.toLowerCase(), "input");
equal(insertTemplate.attr("type"), "checkbox");
editTemplate = field.editTemplate(true);
equal(editTemplate[0].tagName.toLowerCase(), "input");
equal(editTemplate.attr("type"), "checkbox");
equal(editTemplate.is(":checked"), true);
strictEqual(field.filterValue(), undefined);
strictEqual(field.insertValue(), false);
strictEqual(field.editValue(), true);
});
module("jsGrid.field.select");
test("basic", function() {
var field,
filterTemplate,
insertTemplate,
editTemplate;
field = new jsGrid.SelectField({
name: "testField",
items: ["test1", "test2", "test3"],
selectedIndex: 1
});
equal(field.itemTemplate(1), "test2");
filterTemplate = field.filterTemplate();
equal(filterTemplate[0].tagName.toLowerCase(), "select");
equal(filterTemplate.children().length, 3);
insertTemplate = field.insertTemplate();
equal(insertTemplate[0].tagName.toLowerCase(), "select");
equal(insertTemplate.children().length, 3);
editTemplate = field.editTemplate(2);
equal(editTemplate[0].tagName.toLowerCase(), "select");
equal(editTemplate.find("option:selected").length, 1);
ok(editTemplate.children().eq(2).is(":selected"));
strictEqual(field.filterValue(), 1);
strictEqual(field.insertValue(), 1);
strictEqual(field.editValue(), 2);
});
test("items as array of integers", function() {
var field,
filterTemplate,
insertTemplate,
editTemplate;
field = new jsGrid.SelectField({
name: "testField",
items: [0, 10, 20],
selectedIndex: 0
});
strictEqual(field.itemTemplate(0), 0);
filterTemplate = field.filterTemplate();
equal(filterTemplate[0].tagName.toLowerCase(), "select");
equal(filterTemplate.children().length, 3);
insertTemplate = field.insertTemplate();
equal(insertTemplate[0].tagName.toLowerCase(), "select");
equal(insertTemplate.children().length, 3);
editTemplate = field.editTemplate(1);
equal(editTemplate[0].tagName.toLowerCase(), "select");
equal(editTemplate.find("option:selected").length, 1);
ok(editTemplate.children().eq(1).is(":selected"));
strictEqual(field.filterValue(), 0);
strictEqual(field.insertValue(), 0);
strictEqual(field.editValue(), 1);
});
test("string value type", function() {
var field = new jsGrid.SelectField({
name: "testField",
items: [
{ text: "test1", value: "1" },
{ text: "test2", value: "2" },
{ text: "test3", value: "3" }
],
textField: "text",
valueField: "value",
valueType: "string",
selectedIndex: 1
});
field.filterTemplate();
strictEqual(field.filterValue(), "2");
field.editTemplate("2");
strictEqual(field.editValue(), "2");
field.insertTemplate();
strictEqual(field.insertValue(), "2");
});
test("value type auto-defined", function() {
var field = new jsGrid.SelectField({
name: "testField",
items: [
{ text: "test1", value: "1" },
{ text: "test2", value: "2" },
{ text: "test3", value: "3" }
],
textField: "text",
valueField: "value",
selectedIndex: 1
});
strictEqual(field.sorter, "string", "sorter set according to value type");
field.filterTemplate();
strictEqual(field.filterValue(), "2");
field.editTemplate("2");
strictEqual(field.editValue(), "2");
field.insertTemplate();
strictEqual(field.insertValue(), "2");
});
test("value type defaulted to string", function() {
var field = new jsGrid.SelectField({
name: "testField",
items: [
{ text: "test1" },
{ text: "test2", value: "2" }
],
textField: "text",
valueField: "value"
});
strictEqual(field.sorter, "string", "sorter set to string if first item has no value field");
});
test("object items", function() {
var field = new jsGrid.SelectField({
name: "testField",
items: [
{ text: "test1", value: 1 },
{ text: "test2", value: 2 },
{ text: "test3", value: 3 }
]
});
strictEqual(field.itemTemplate(1), field.items[1]);
field.textField = "text";
strictEqual(field.itemTemplate(1), "test2");
field.textField = "";
field.valueField = "value";
strictEqual(field.itemTemplate(1), field.items[0]);
ok(field.editTemplate(2));
strictEqual(field.editValue(), 2);
field.textField = "text";
strictEqual(field.itemTemplate(1), "test1");
});
module("jsGrid.field.control");
test("basic", function() {
var field,
itemTemplate,
headerTemplate,
filterTemplate,
insertTemplate,
editTemplate;
field = new jsGrid.ControlField();
field._grid = {
filtering: true,
inserting: true,
option: $.noop
};
itemTemplate = field.itemTemplate("any_value");
equal(itemTemplate.filter("." + field.editButtonClass).length, 1);
equal(itemTemplate.filter("." + field.deleteButtonClass).length, 1);
headerTemplate = field.headerTemplate();
equal(headerTemplate.filter("." + field.insertModeButtonClass).length, 1);
var $modeSwitchButton = headerTemplate.filter("." + field.modeButtonClass);
$modeSwitchButton.trigger("click");
equal(headerTemplate.filter("." + field.searchModeButtonClass).length, 1);
filterTemplate = field.filterTemplate();
equal(filterTemplate.filter("." + field.searchButtonClass).length, 1);
equal(filterTemplate.filter("." + field.clearFilterButtonClass).length, 1);
insertTemplate = field.insertTemplate();
equal(insertTemplate.filter("." + field.insertButtonClass).length, 1);
editTemplate = field.editTemplate("any_value");
equal(editTemplate.filter("." + field.updateButtonClass).length, 1);
equal(editTemplate.filter("." + field.cancelEditButtonClass).length, 1);
strictEqual(field.filterValue(), "");
strictEqual(field.insertValue(), "");
strictEqual(field.editValue(), "");
});
test("switchMode button should consider filtering=false", function() {
var optionArgs = {};
var field = new jsGrid.ControlField();
field._grid = {
filtering: false,
inserting: true,
option: function(name, value) {
optionArgs = {
name: name,
value: value
};
}
};
var headerTemplate = field.headerTemplate();
equal(headerTemplate.filter("." + field.insertModeButtonClass).length, 1, "inserting switch button rendered");
var $modeSwitchButton = headerTemplate.filter("." + field.modeButtonClass);
$modeSwitchButton.trigger("click");
ok($modeSwitchButton.hasClass(field.modeOnButtonClass), "on class is attached");
equal(headerTemplate.filter("." + field.insertModeButtonClass).length, 1, "insert button rendered");
equal(headerTemplate.filter("." + field.searchModeButtonClass).length, 0, "search button not rendered");
deepEqual(optionArgs, { name: "inserting", value: true }, "turn on grid inserting mode");
$modeSwitchButton.trigger("click");
ok(!$modeSwitchButton.hasClass(field.modeOnButtonClass), "on class is detached");
deepEqual(optionArgs, { name: "inserting", value: false }, "turn off grid inserting mode");
});
test("switchMode button should consider inserting=false", function() {
var optionArgs = {};
var field = new jsGrid.ControlField();
field._grid = {
filtering: true,
inserting: false,
option: function(name, value) {
optionArgs = {
name: name,
value: value
};
}
};
var headerTemplate = field.headerTemplate();
equal(headerTemplate.filter("." + field.searchModeButtonClass).length, 1, "filtering switch button rendered");
var $modeSwitchButton = headerTemplate.filter("." + field.modeButtonClass);
$modeSwitchButton.trigger("click");
ok(!$modeSwitchButton.hasClass(field.modeOnButtonClass), "on class is detached");
equal(headerTemplate.filter("." + field.searchModeButtonClass).length, 1, "search button rendered");
equal(headerTemplate.filter("." + field.insertModeButtonClass).length, 0, "insert button not rendered");
deepEqual(optionArgs, { name: "filtering", value: false }, "turn off grid filtering mode");
$modeSwitchButton.trigger("click");
ok($modeSwitchButton.hasClass(field.modeOnButtonClass), "on class is attached");
deepEqual(optionArgs, { name: "filtering", value: true }, "turn on grid filtering mode");
});
test("switchMode is not rendered if inserting=false and filtering=false", function() {
var optionArgs = {};
var field = new jsGrid.ControlField();
field._grid = {
filtering: false,
inserting: false
};
var headerTemplate = field.headerTemplate();
strictEqual(headerTemplate, "", "empty header");
});
});
<MSG> Tests: Remove redundant console.log
<DFF> @@ -51,7 +51,6 @@ $(function() {
var editTemplateContent = editTemplate instanceof jQuery ? editTemplate[0].outerHTML : editTemplate;
var itemTemplateContent = itemTemplate instanceof jQuery ? itemTemplate[0].outerHTML : itemTemplate;
-console.log(name + ": " + editTemplateContent);
equal(editTemplateContent, itemTemplateContent, "item template is rendered instead of edit template for field " + name);
});
});
| 0 | Tests: Remove redundant console.log | 1 | .js | field | mit | tabalinas/jsgrid |
10059867 | <NME> jsgrid.field.tests.js
<BEF> $(function() {
var Grid = jsGrid.Grid;
module("common field config", {
setup: function() {
this.isFieldExcluded = function(FieldClass) {
return FieldClass === jsGrid.ControlField;
};
}
});
test("filtering=false prevents rendering filter template", function() {
var isFieldExcluded = this.isFieldExcluded;
$.each(jsGrid.fields, function(name, FieldClass) {
if(isFieldExcluded(FieldClass))
return;
var field = new FieldClass({ filtering: false });
equal(field.filterTemplate(), "", "empty filter template for field " + name);
});
});
test("inserting=false prevents rendering insert template", function() {
var isFieldExcluded = this.isFieldExcluded;
$.each(jsGrid.fields, function(name, FieldClass) {
if(isFieldExcluded(FieldClass))
return;
var field = new FieldClass({ inserting: false });
equal(field.insertTemplate(), "", "empty insert template for field " + name);
});
});
test("editing=false renders itemTemplate", function() {
var isFieldExcluded = this.isFieldExcluded;
$.each(jsGrid.fields, function(name, FieldClass) {
if(isFieldExcluded(FieldClass))
return;
var item = {
field: "test"
};
var args;
var editTemplateContent = editTemplate instanceof jQuery ? editTemplate[0].outerHTML : editTemplate;
var itemTemplateContent = itemTemplate instanceof jQuery ? itemTemplate[0].outerHTML : itemTemplate;
console.log(name + ": " + editTemplateContent);
equal(editTemplateContent, itemTemplateContent, "item template is rendered instead of edit template for field " + name);
});
});
});
var itemTemplate = field.itemTemplate("test", item);
var editTemplate = field.editTemplate("test", item);
var editTemplateContent = editTemplate instanceof jQuery ? editTemplate[0].outerHTML : editTemplate;
var itemTemplateContent = itemTemplate instanceof jQuery ? itemTemplate[0].outerHTML : itemTemplate;
equal(editTemplateContent, itemTemplateContent, "item template is rendered instead of edit template for " + name);
equal(args.length, 2, "passed both arguments for " + name);
equal(args[0], "test", "field value passed as a first argument for " + name);
equal(args[1], item, "item passed as a second argument for " + name);
});
});
module("jsGrid.field");
test("basic", function() {
var customSortingFunc = function() {
return 1;
},
field = new jsGrid.Field({
name: "testField",
title: "testTitle",
sorter: customSortingFunc
});
equal(field.headerTemplate(), "testTitle");
equal(field.itemTemplate("testValue"), "testValue");
equal(field.filterTemplate(), "");
equal(field.insertTemplate(), "");
equal(field.editTemplate("testValue"), "testValue");
strictEqual(field.filterValue(), "");
strictEqual(field.insertValue(), "");
strictEqual(field.editValue(), "testValue");
strictEqual(field.sortingFunc, customSortingFunc);
});
module("jsGrid.field.text");
test("basic", function() {
var field = new jsGrid.TextField({ name: "testField" });
equal(field.itemTemplate("testValue"), "testValue");
equal(field.filterTemplate()[0].tagName.toLowerCase(), "input");
equal(field.insertTemplate()[0].tagName.toLowerCase(), "input");
equal(field.editTemplate("testEditValue")[0].tagName.toLowerCase(), "input");
strictEqual(field.filterValue(), "");
strictEqual(field.insertValue(), "");
strictEqual(field.editValue(), "testEditValue");
});
test("set default field options with setDefaults", function() {
jsGrid.setDefaults("text", {
defaultOption: "test"
});
var $element = $("#jsGrid").jsGrid({
fields: [{ type: "text" }]
});
equal($element.jsGrid("option", "fields")[0].defaultOption, "test", "default field option set");
});
module("jsGrid.field.number");
test("basic", function() {
var field = new jsGrid.NumberField({ name: "testField" });
equal(field.itemTemplate(5), "5");
equal(field.filterTemplate()[0].tagName.toLowerCase(), "input");
equal(field.insertTemplate()[0].tagName.toLowerCase(), "input");
equal(field.editTemplate(6)[0].tagName.toLowerCase(), "input");
strictEqual(field.filterValue(), undefined);
strictEqual(field.insertValue(), undefined);
strictEqual(field.editValue(), 6);
});
module("jsGrid.field.textArea");
test("basic", function() {
var field = new jsGrid.TextAreaField({ name: "testField" });
equal(field.itemTemplate("testValue"), "testValue");
equal(field.filterTemplate()[0].tagName.toLowerCase(), "input");
equal(field.insertTemplate()[0].tagName.toLowerCase(), "textarea");
equal(field.editTemplate("testEditValue")[0].tagName.toLowerCase(), "textarea");
strictEqual(field.insertValue(), "");
strictEqual(field.editValue(), "testEditValue");
});
module("jsGrid.field.checkbox");
test("basic", function() {
var field = new jsGrid.CheckboxField({ name: "testField" }),
itemTemplate,
filterTemplate,
insertTemplate,
editTemplate;
itemTemplate = field.itemTemplate("testValue");
equal(itemTemplate[0].tagName.toLowerCase(), "input");
equal(itemTemplate.attr("type"), "checkbox");
equal(itemTemplate.attr("disabled"), "disabled");
filterTemplate = field.filterTemplate();
equal(filterTemplate[0].tagName.toLowerCase(), "input");
equal(filterTemplate.attr("type"), "checkbox");
equal(filterTemplate.prop("indeterminate"), true);
insertTemplate = field.insertTemplate();
equal(insertTemplate[0].tagName.toLowerCase(), "input");
equal(insertTemplate.attr("type"), "checkbox");
editTemplate = field.editTemplate(true);
equal(editTemplate[0].tagName.toLowerCase(), "input");
equal(editTemplate.attr("type"), "checkbox");
equal(editTemplate.is(":checked"), true);
strictEqual(field.filterValue(), undefined);
strictEqual(field.insertValue(), false);
strictEqual(field.editValue(), true);
});
module("jsGrid.field.select");
test("basic", function() {
var field,
filterTemplate,
insertTemplate,
editTemplate;
field = new jsGrid.SelectField({
name: "testField",
items: ["test1", "test2", "test3"],
selectedIndex: 1
});
equal(field.itemTemplate(1), "test2");
filterTemplate = field.filterTemplate();
equal(filterTemplate[0].tagName.toLowerCase(), "select");
equal(filterTemplate.children().length, 3);
insertTemplate = field.insertTemplate();
equal(insertTemplate[0].tagName.toLowerCase(), "select");
equal(insertTemplate.children().length, 3);
editTemplate = field.editTemplate(2);
equal(editTemplate[0].tagName.toLowerCase(), "select");
equal(editTemplate.find("option:selected").length, 1);
ok(editTemplate.children().eq(2).is(":selected"));
strictEqual(field.filterValue(), 1);
strictEqual(field.insertValue(), 1);
strictEqual(field.editValue(), 2);
});
test("items as array of integers", function() {
var field,
filterTemplate,
insertTemplate,
editTemplate;
field = new jsGrid.SelectField({
name: "testField",
items: [0, 10, 20],
selectedIndex: 0
});
strictEqual(field.itemTemplate(0), 0);
filterTemplate = field.filterTemplate();
equal(filterTemplate[0].tagName.toLowerCase(), "select");
equal(filterTemplate.children().length, 3);
insertTemplate = field.insertTemplate();
equal(insertTemplate[0].tagName.toLowerCase(), "select");
equal(insertTemplate.children().length, 3);
editTemplate = field.editTemplate(1);
equal(editTemplate[0].tagName.toLowerCase(), "select");
equal(editTemplate.find("option:selected").length, 1);
ok(editTemplate.children().eq(1).is(":selected"));
strictEqual(field.filterValue(), 0);
strictEqual(field.insertValue(), 0);
strictEqual(field.editValue(), 1);
});
test("string value type", function() {
var field = new jsGrid.SelectField({
name: "testField",
items: [
{ text: "test1", value: "1" },
{ text: "test2", value: "2" },
{ text: "test3", value: "3" }
],
textField: "text",
valueField: "value",
valueType: "string",
selectedIndex: 1
});
field.filterTemplate();
strictEqual(field.filterValue(), "2");
field.editTemplate("2");
strictEqual(field.editValue(), "2");
field.insertTemplate();
strictEqual(field.insertValue(), "2");
});
test("value type auto-defined", function() {
var field = new jsGrid.SelectField({
name: "testField",
items: [
{ text: "test1", value: "1" },
{ text: "test2", value: "2" },
{ text: "test3", value: "3" }
],
textField: "text",
valueField: "value",
selectedIndex: 1
});
strictEqual(field.sorter, "string", "sorter set according to value type");
field.filterTemplate();
strictEqual(field.filterValue(), "2");
field.editTemplate("2");
strictEqual(field.editValue(), "2");
field.insertTemplate();
strictEqual(field.insertValue(), "2");
});
test("value type defaulted to string", function() {
var field = new jsGrid.SelectField({
name: "testField",
items: [
{ text: "test1" },
{ text: "test2", value: "2" }
],
textField: "text",
valueField: "value"
});
strictEqual(field.sorter, "string", "sorter set to string if first item has no value field");
});
test("object items", function() {
var field = new jsGrid.SelectField({
name: "testField",
items: [
{ text: "test1", value: 1 },
{ text: "test2", value: 2 },
{ text: "test3", value: 3 }
]
});
strictEqual(field.itemTemplate(1), field.items[1]);
field.textField = "text";
strictEqual(field.itemTemplate(1), "test2");
field.textField = "";
field.valueField = "value";
strictEqual(field.itemTemplate(1), field.items[0]);
ok(field.editTemplate(2));
strictEqual(field.editValue(), 2);
field.textField = "text";
strictEqual(field.itemTemplate(1), "test1");
});
module("jsGrid.field.control");
test("basic", function() {
var field,
itemTemplate,
headerTemplate,
filterTemplate,
insertTemplate,
editTemplate;
field = new jsGrid.ControlField();
field._grid = {
filtering: true,
inserting: true,
option: $.noop
};
itemTemplate = field.itemTemplate("any_value");
equal(itemTemplate.filter("." + field.editButtonClass).length, 1);
equal(itemTemplate.filter("." + field.deleteButtonClass).length, 1);
headerTemplate = field.headerTemplate();
equal(headerTemplate.filter("." + field.insertModeButtonClass).length, 1);
var $modeSwitchButton = headerTemplate.filter("." + field.modeButtonClass);
$modeSwitchButton.trigger("click");
equal(headerTemplate.filter("." + field.searchModeButtonClass).length, 1);
filterTemplate = field.filterTemplate();
equal(filterTemplate.filter("." + field.searchButtonClass).length, 1);
equal(filterTemplate.filter("." + field.clearFilterButtonClass).length, 1);
insertTemplate = field.insertTemplate();
equal(insertTemplate.filter("." + field.insertButtonClass).length, 1);
editTemplate = field.editTemplate("any_value");
equal(editTemplate.filter("." + field.updateButtonClass).length, 1);
equal(editTemplate.filter("." + field.cancelEditButtonClass).length, 1);
strictEqual(field.filterValue(), "");
strictEqual(field.insertValue(), "");
strictEqual(field.editValue(), "");
});
test("switchMode button should consider filtering=false", function() {
var optionArgs = {};
var field = new jsGrid.ControlField();
field._grid = {
filtering: false,
inserting: true,
option: function(name, value) {
optionArgs = {
name: name,
value: value
};
}
};
var headerTemplate = field.headerTemplate();
equal(headerTemplate.filter("." + field.insertModeButtonClass).length, 1, "inserting switch button rendered");
var $modeSwitchButton = headerTemplate.filter("." + field.modeButtonClass);
$modeSwitchButton.trigger("click");
ok($modeSwitchButton.hasClass(field.modeOnButtonClass), "on class is attached");
equal(headerTemplate.filter("." + field.insertModeButtonClass).length, 1, "insert button rendered");
equal(headerTemplate.filter("." + field.searchModeButtonClass).length, 0, "search button not rendered");
deepEqual(optionArgs, { name: "inserting", value: true }, "turn on grid inserting mode");
$modeSwitchButton.trigger("click");
ok(!$modeSwitchButton.hasClass(field.modeOnButtonClass), "on class is detached");
deepEqual(optionArgs, { name: "inserting", value: false }, "turn off grid inserting mode");
});
test("switchMode button should consider inserting=false", function() {
var optionArgs = {};
var field = new jsGrid.ControlField();
field._grid = {
filtering: true,
inserting: false,
option: function(name, value) {
optionArgs = {
name: name,
value: value
};
}
};
var headerTemplate = field.headerTemplate();
equal(headerTemplate.filter("." + field.searchModeButtonClass).length, 1, "filtering switch button rendered");
var $modeSwitchButton = headerTemplate.filter("." + field.modeButtonClass);
$modeSwitchButton.trigger("click");
ok(!$modeSwitchButton.hasClass(field.modeOnButtonClass), "on class is detached");
equal(headerTemplate.filter("." + field.searchModeButtonClass).length, 1, "search button rendered");
equal(headerTemplate.filter("." + field.insertModeButtonClass).length, 0, "insert button not rendered");
deepEqual(optionArgs, { name: "filtering", value: false }, "turn off grid filtering mode");
$modeSwitchButton.trigger("click");
ok($modeSwitchButton.hasClass(field.modeOnButtonClass), "on class is attached");
deepEqual(optionArgs, { name: "filtering", value: true }, "turn on grid filtering mode");
});
test("switchMode is not rendered if inserting=false and filtering=false", function() {
var optionArgs = {};
var field = new jsGrid.ControlField();
field._grid = {
filtering: false,
inserting: false
};
var headerTemplate = field.headerTemplate();
strictEqual(headerTemplate, "", "empty header");
});
});
<MSG> Tests: Remove redundant console.log
<DFF> @@ -51,7 +51,6 @@ $(function() {
var editTemplateContent = editTemplate instanceof jQuery ? editTemplate[0].outerHTML : editTemplate;
var itemTemplateContent = itemTemplate instanceof jQuery ? itemTemplate[0].outerHTML : itemTemplate;
-console.log(name + ": " + editTemplateContent);
equal(editTemplateContent, itemTemplateContent, "item template is rendered instead of edit template for field " + name);
});
});
| 0 | Tests: Remove redundant console.log | 1 | .js | field | mit | tabalinas/jsgrid |
10059868 | <NME> TextDocument.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
namespace AvaloniaEdit.Document
{
/// <summary>
/// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events.
/// </summary>
/// <remarks>
/// <b>Thread safety:</b>
/// <inheritdoc cref="VerifyAccess"/>
/// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para>
/// </remarks>
public sealed class TextDocument : IDocument, INotifyPropertyChanged
{
#region Thread ownership
private readonly object _lockObject = new object();
#endregion
#region Fields + Constructor
private readonly Rope<char> _rope;
private readonly DocumentLineTree _lineTree;
private readonly LineManager _lineManager;
private readonly TextAnchorTree _anchorTree;
private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider();
/// <summary>
/// Create an empty text document.
/// </summary>
public TextDocument()
: this(string.Empty.ToCharArray())
{
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(IEnumerable<char> initialText)
{
if (initialText == null)
throw new ArgumentNullException(nameof(initialText));
_rope = new Rope<char>(initialText);
_lineTree = new DocumentLineTree(this);
_lineManager = new LineManager(_lineTree, this);
_lineTrackers.CollectionChanged += delegate
{
_lineManager.UpdateListOfLineTrackers();
};
_anchorTree = new TextAnchorTree(this);
_undoStack = new UndoStack();
FireChangeEvents();
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(ITextSource initialText)
: this(GetTextFromTextSource(initialText))
{
}
// gets the text from a text source, directly retrieving the underlying rope where possible
private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource)
{
if (textSource == null)
throw new ArgumentNullException(nameof(textSource));
if (textSource is RopeTextSource rts)
{
return rts.GetRope();
}
if (textSource is TextDocument doc)
{
return doc._rope;
}
return textSource.Text.ToCharArray();
}
#endregion
#region Text
private void ThrowIfRangeInvalid(int offset, int length)
{
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
if (length < 0 || offset + length > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
}
/// <inheritdoc/>
public string GetText(int offset, int length)
{
VerifyAccess();
return _rope.ToString(offset, length);
}
private void VerifyAccess()
{
Dispatcher.UIThread.VerifyAccess();
}
/// <summary>
public void SetOwnerThread(Thread newOwner)
{
// We need to lock here to ensure that in the null owner case,
// only one thread succeeds in taking ownership.
lock (_lockObject) {
if (ownerThread != null) {
VerifyAccess();
}
ownerThread = newOwner;
}
}
private void VerifyAccess()
{
if(Thread.CurrentThread != ownerThread)
{
throw new InvalidOperationException("Call from invalid thread.");
}
}
/// <summary>
/// Retrieves the text for a portion of the document.
/// </summary>
public string GetText(ISegment segment)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
return GetText(segment.Offset, segment.Length);
}
/// <inheritdoc/>
public int IndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.IndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int LastIndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.LastIndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int IndexOfAny(char[] anyOf, int startIndex, int count)
{
DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds
return _rope.IndexOfAny(anyOf, startIndex, count);
}
/// <inheritdoc/>
public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.IndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.LastIndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public char GetCharAt(int offset)
{
DebugVerifyAccess(); // frequently called, so must be fast in release builds
return _rope[offset];
}
private WeakReference _cachedText;
/// <summary>
/// Gets/Sets the text of the whole document.
/// </summary>
public string Text
{
get
{
VerifyAccess();
var completeText = _cachedText?.Target as string;
if (completeText == null)
{
completeText = _rope.ToString();
_cachedText = new WeakReference(completeText);
}
return completeText;
}
set
{
VerifyAccess();
if (value == null)
throw new ArgumentNullException(nameof(value));
Replace(0, _rope.Length, value);
}
}
/// <summary>
/// This event is called after a group of changes is completed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextChanged;
event EventHandler IDocument.ChangeCompleted
{
add => TextChanged += value;
remove => TextChanged -= value;
}
/// <inheritdoc/>
public int TextLength
{
get
{
VerifyAccess();
return _rope.Length;
}
}
/// <summary>
/// Is raised when the TextLength property changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextLengthChanged;
/// <summary>
/// Is raised before the document changes.
/// </summary>
/// <remarks>
/// <para>Here is the order in which events are raised during a document update:</para>
/// <list type="bullet">
/// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description>Start of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateStarted"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="Changing"/> event is raised</description></item>
/// <item><description>The document is changed</description></item>
/// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were
/// in the deleted text portion</description></item>
/// <item><description><see cref="Changed"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="TextChanged"/> event is raised</description></item>
/// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item>
/// <item><description>End of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateFinished"/> event is raised</description></item>
/// </list></item>
/// </list>
/// <para>
/// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>,
/// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>.
/// </para><para>
/// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls.
/// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done.
/// </para><para>
/// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step.
/// </para>
/// </remarks>
public event EventHandler<DocumentChangeEventArgs> Changing;
// Unfortunately EventHandler<T> is invariant, so we have to use two separate events
private event EventHandler<TextChangeEventArgs> TextChangingInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanging
{
add => TextChangingInternal += value;
remove => TextChangingInternal -= value;
}
/// <summary>
/// Is raised after the document has changed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler<DocumentChangeEventArgs> Changed;
private event EventHandler<TextChangeEventArgs> TextChangedInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanged
{
add => TextChangedInternal += value;
remove => TextChangedInternal -= value;
}
/// <summary>
/// Creates a snapshot of the current text.
/// </summary>
/// <remarks>
/// <para>This method returns an immutable snapshot of the document, and may be safely called even when
/// the document's owner thread is concurrently modifying the document.
/// </para><para>
/// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other
/// classes implementing ITextSource.CreateSnapshot().
/// </para><para>
/// </para>
/// </remarks>
public ITextSource CreateSnapshot()
{
lock (_lockObject)
{
return new RopeTextSource(_rope, _versionProvider.CurrentVersion);
}
}
/// <summary>
/// Creates a snapshot of a part of the current text.
/// </summary>
/// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks>
public ITextSource CreateSnapshot(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextSource(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public ITextSourceVersion Version => _versionProvider.CurrentVersion;
/// <inheritdoc/>
public TextReader CreateReader()
{
lock (_lockObject)
{
return new RopeTextReader(_rope);
}
}
/// <inheritdoc/>
public TextReader CreateReader(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextReader(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer)
{
VerifyAccess();
_rope.WriteTo(writer, 0, _rope.Length);
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer, int offset, int length)
{
VerifyAccess();
_rope.WriteTo(writer, offset, length);
}
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region BeginUpdate / EndUpdate
private int _beginUpdateCount;
/// <summary>
/// Gets if an update is running.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public bool IsInUpdate
{
get
{
VerifyAccess();
return _beginUpdateCount > 0;
}
}
/// <summary>
/// Immediately calls <see cref="BeginUpdate()"/>,
/// and returns an IDisposable that calls <see cref="EndUpdate()"/>.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public IDisposable RunUpdate()
{
BeginUpdate();
return new CallbackOnDispose(EndUpdate);
}
/// <summary>
/// <para>Begins a group of document changes.</para>
/// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will
/// group all changes into a single action.</para>
/// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number
/// of EndUpdate calls the events resume their work.</para>
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void BeginUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot change document within another document change.");
_beginUpdateCount++;
if (_beginUpdateCount == 1)
{
_undoStack.StartUndoGroup();
UpdateStarted?.Invoke(this, EventArgs.Empty);
}
}
/// <summary>
/// Ends a group of document changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void EndUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot end update within document change.");
if (_beginUpdateCount == 0)
throw new InvalidOperationException("No update is active.");
if (_beginUpdateCount == 1)
{
// fire change events inside the change group - event handlers might add additional
// document changes to the change group
FireChangeEvents();
_undoStack.EndUndoGroup();
_beginUpdateCount = 0;
UpdateFinished?.Invoke(this, EventArgs.Empty);
}
else
{
_beginUpdateCount -= 1;
}
}
/// <summary>
/// Occurs when a document change starts.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateStarted;
/// <summary>
/// Occurs when a document change is finished.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateFinished;
void IDocument.StartUndoableAction()
{
BeginUpdate();
}
void IDocument.EndUndoableAction()
{
EndUpdate();
}
IDisposable IDocument.OpenUndoGroup()
{
return RunUpdate();
}
#endregion
#region Fire events after update
private int _oldTextLength;
private int _oldLineCount;
private bool _fireTextChanged;
/// <summary>
/// Fires TextChanged, TextLengthChanged, LineCountChanged if required.
/// </summary>
internal void FireChangeEvents()
{
// it may be necessary to fire the event multiple times if the document is changed
// from inside the event handlers
while (_fireTextChanged)
{
_fireTextChanged = false;
TextChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("Text");
var textLength = _rope.Length;
if (textLength != _oldTextLength)
{
_oldTextLength = textLength;
TextLengthChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("TextLength");
}
var lineCount = _lineTree.LineCount;
if (lineCount != _oldLineCount)
{
_oldLineCount = lineCount;
LineCountChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("LineCount");
}
}
}
#endregion
#region Insert / Remove / Replace
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, string text)
{
Replace(offset, 0, new StringTextSource(text), null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, ITextSource text)
{
Replace(offset, 0, text, null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, new StringTextSource(text), null);
}
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, text, null);
}
}
/// <summary>
/// Removes text.
/// </summary>
public void Remove(ISegment segment)
{
Replace(segment, string.Empty);
}
/// <summary>
/// Removes text.
/// </summary>
/// <param name="offset">Starting offset of the text to be removed.</param>
/// <param name="length">Length of the text to be removed.</param>
public void Remove(int offset, int length)
{
Replace(offset, length, StringTextSource.Empty);
}
internal bool InDocumentChanging;
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, string text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, ITextSource text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, string text)
{
Replace(offset, length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, ITextSource text)
{
Replace(offset, length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMappingType);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType)
{
if (text == null)
throw new ArgumentNullException(nameof(text));
// Please see OffsetChangeMappingType XML comments for details on how these modes work.
switch (offsetChangeMappingType)
{
case OffsetChangeMappingType.Normal:
Replace(offset, length, text, null);
break;
case OffsetChangeMappingType.KeepAnchorBeforeInsertion:
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(
new OffsetChangeMapEntry(offset, length, text.TextLength, false, true)));
break;
case OffsetChangeMappingType.RemoveAndInsert:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else
{
var map = new OffsetChangeMap(2)
{
new OffsetChangeMapEntry(offset, length, 0),
new OffsetChangeMapEntry(offset, 0, text.TextLength)
};
map.Freeze();
Replace(offset, length, text, map);
}
break;
case OffsetChangeMappingType.CharacterReplace:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else if (text.TextLength > length)
{
// look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace
// the last character
var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else if (text.TextLength < length)
{
var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else
{
Replace(offset, length, text, OffsetChangeMap.Empty);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value");
}
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMap);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap)
{
text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text));
offsetChangeMap?.Freeze();
// Ensure that all changes take place inside an update group.
// Will also take care of throwing an exception if inDocumentChanging is set.
BeginUpdate();
try
{
// protect document change against corruption by other changes inside the event handlers
InDocumentChanging = true;
try
{
// The range verification must wait until after the BeginUpdate() call because the document
// might be modified inside the UpdateStarted event.
ThrowIfRangeInvalid(offset, length);
DoReplace(offset, length, text, offsetChangeMap);
}
finally
{
InDocumentChanging = false;
}
}
finally
{
EndUpdate();
}
}
private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap)
{
if (length == 0 && newText.TextLength == 0)
return;
// trying to replace a single character in 'Normal' mode?
// for single characters, 'CharacterReplace' mode is equivalent, but more performant
// (we don't have to touch the anchorTree at all in 'CharacterReplace' mode)
if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null)
offsetChangeMap = OffsetChangeMap.Empty;
ITextSource removedText;
if (length == 0)
{
removedText = StringTextSource.Empty;
}
else if (length < 100)
{
removedText = new StringTextSource(_rope.ToString(offset, length));
}
else
{
// use a rope if the removed string is long
removedText = new RopeTextSource(_rope.GetRange(offset, length));
}
var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap);
// fire DocumentChanging event
Changing?.Invoke(this, args);
TextChangingInternal?.Invoke(this, args);
_undoStack.Push(this, args);
_cachedText = null; // reset cache of complete document text
_fireTextChanged = true;
var delayedEvents = new DelayedEvents();
lock (_lockObject)
{
// create linked list of checkpoints
_versionProvider.AppendChange(args);
// now update the textBuffer and lineTree
if (offset == 0 && length == _rope.Length)
{
// optimize replacing the whole document
_rope.Clear();
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(0, newRopeTextSource.GetRope());
else
_rope.InsertText(0, newText.Text);
_lineManager.Rebuild();
}
else
{
_rope.RemoveRange(offset, length);
_lineManager.Remove(offset, length);
#if DEBUG
_lineTree.CheckProperties();
#endif
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(offset, newRopeTextSource.GetRope());
else
_rope.InsertText(offset, newText.Text);
_lineManager.Insert(offset, newText);
#if DEBUG
_lineTree.CheckProperties();
#endif
}
}
// update text anchors
if (offsetChangeMap == null)
{
_anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents);
}
else
{
foreach (var entry in offsetChangeMap)
{
_anchorTree.HandleTextChange(entry, delayedEvents);
}
}
_lineManager.ChangeComplete(args);
// raise delayed events after our data structures are consistent again
delayedEvents.RaiseEvents();
// fire DocumentChanged event
Changed?.Invoke(this, args);
TextChangedInternal?.Invoke(this, args);
}
#endregion
#region GetLineBy...
/// <summary>
/// Gets a read-only list of lines.
/// </summary>
/// <remarks><inheritdoc cref="DocumentLine"/></remarks>
public IList<DocumentLine> Lines => _lineTree;
/// <summary>
/// Gets a line by the line number: O(log n)
/// </summary>
public DocumentLine GetLineByNumber(int number)
{
VerifyAccess();
if (number < 1 || number > _lineTree.LineCount)
throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount);
return _lineTree.GetByNumber(number);
}
IDocumentLine IDocument.GetLineByNumber(int lineNumber)
{
return GetLineByNumber(lineNumber);
}
/// <summary>
/// Gets a document lines by offset.
/// Runtime: O(log n)
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")]
public DocumentLine GetLineByOffset(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length);
}
return _lineTree.GetByOffset(offset);
}
IDocumentLine IDocument.GetLineByOffset(int offset)
{
return GetLineByOffset(offset);
}
#endregion
#region GetOffset / GetLocation
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(TextLocation location)
{
return GetOffset(location.Line, location.Column);
}
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(int line, int column)
{
var docLine = GetLineByNumber(line);
if (column <= 0)
return docLine.Offset;
if (column > docLine.Length)
return docLine.EndOffset;
return docLine.Offset + column - 1;
}
/// <summary>
/// Gets the location from an offset.
/// </summary>
/// <seealso cref="GetOffset(TextLocation)"/>
public TextLocation GetLocation(int offset)
{
var line = GetLineByOffset(offset);
return new TextLocation(line.LineNumber, offset - line.Offset + 1);
}
#endregion
#region Line Trackers
private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>();
/// <summary>
/// Gets the list of <see cref="ILineTracker"/>s attached to this document.
/// You can add custom line trackers to this list.
/// </summary>
public IList<ILineTracker> LineTrackers
{
get
{
VerifyAccess();
return _lineTrackers;
}
}
#endregion
#region UndoStack
public UndoStack _undoStack;
/// <summary>
/// Gets the <see cref="UndoStack"/> of the document.
/// </summary>
/// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks>
public UndoStack UndoStack
{
get => _undoStack;
set
{
if (value == null)
throw new ArgumentNullException();
if (value != _undoStack)
{
_undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document
// ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress)
_undoStack = value;
OnPropertyChanged("UndoStack");
}
}
}
#endregion
#region CreateAnchor
/// <summary>
/// Creates a new <see cref="TextAnchor"/> at the specified offset.
/// </summary>
/// <inheritdoc cref="TextAnchor" select="remarks|example"/>
public TextAnchor CreateAnchor(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
return _anchorTree.CreateAnchor(offset);
}
ITextAnchor IDocument.CreateAnchor(int offset)
{
return CreateAnchor(offset);
}
#endregion
#region LineCount
/// <summary>
/// Gets the total number of lines in the document.
/// Runtime: O(1).
/// </summary>
public int LineCount
{
get
{
VerifyAccess();
return _lineTree.LineCount;
}
}
/// <summary>
/// Is raised when the LineCount property changes.
/// </summary>
public event EventHandler LineCountChanged;
#endregion
#region Debugging
[Conditional("DEBUG")]
internal void DebugVerifyAccess()
{
VerifyAccess();
}
/// <summary>
/// Gets the document lines tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetLineTreeAsString()
{
#if DEBUG
return _lineTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
/// <summary>
/// Gets the text anchor tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetTextAnchorTreeAsString()
{
#if DEBUG
return _anchorTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
#endregion
#region Service Provider
private IServiceProvider _serviceProvider;
internal IServiceProvider ServiceProvider
{
get
{
VerifyAccess();
if (_serviceProvider == null)
{
var container = new ServiceContainer();
container.AddService(this);
container.AddService<IDocument>(this);
_serviceProvider = container;
}
return _serviceProvider;
}
set
{
VerifyAccess();
_serviceProvider = value ?? throw new ArgumentNullException(nameof(value));
}
}
object IServiceProvider.GetService(Type serviceType)
{
return ServiceProvider.GetService(serviceType);
}
#endregion
#region FileName
private string _fileName;
/// <inheritdoc/>
public event EventHandler FileNameChanged;
private void OnFileNameChanged(EventArgs e)
{
FileNameChanged?.Invoke(this, e);
}
/// <inheritdoc/>
public string FileName
{
get { return _fileName; }
set
{
if (_fileName != value)
{
_fileName = value;
OnFileNameChanged(EventArgs.Empty);
}
}
}
#endregion
}
}
<MSG> Merge pull request #51 from danwalmsley/fix-thread-verification
verify access checks against thread textdocument is created on.
<DFF> @@ -26,6 +26,7 @@ using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
+using System.Threading;
namespace AvaloniaEdit.Document
{
@@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document
return _rope.ToString(offset, length);
}
+ private Thread ownerThread = Thread.CurrentThread;
+
private void VerifyAccess()
{
- Dispatcher.UIThread.VerifyAccess();
+ if(Thread.CurrentThread != ownerThread)
+ {
+ throw new InvalidOperationException("Call from invalid thread.");
+ }
}
/// <summary>
| 7 | Merge pull request #51 from danwalmsley/fix-thread-verification | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059869 | <NME> TextDocument.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
namespace AvaloniaEdit.Document
{
/// <summary>
/// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events.
/// </summary>
/// <remarks>
/// <b>Thread safety:</b>
/// <inheritdoc cref="VerifyAccess"/>
/// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para>
/// </remarks>
public sealed class TextDocument : IDocument, INotifyPropertyChanged
{
#region Thread ownership
private readonly object _lockObject = new object();
#endregion
#region Fields + Constructor
private readonly Rope<char> _rope;
private readonly DocumentLineTree _lineTree;
private readonly LineManager _lineManager;
private readonly TextAnchorTree _anchorTree;
private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider();
/// <summary>
/// Create an empty text document.
/// </summary>
public TextDocument()
: this(string.Empty.ToCharArray())
{
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(IEnumerable<char> initialText)
{
if (initialText == null)
throw new ArgumentNullException(nameof(initialText));
_rope = new Rope<char>(initialText);
_lineTree = new DocumentLineTree(this);
_lineManager = new LineManager(_lineTree, this);
_lineTrackers.CollectionChanged += delegate
{
_lineManager.UpdateListOfLineTrackers();
};
_anchorTree = new TextAnchorTree(this);
_undoStack = new UndoStack();
FireChangeEvents();
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(ITextSource initialText)
: this(GetTextFromTextSource(initialText))
{
}
// gets the text from a text source, directly retrieving the underlying rope where possible
private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource)
{
if (textSource == null)
throw new ArgumentNullException(nameof(textSource));
if (textSource is RopeTextSource rts)
{
return rts.GetRope();
}
if (textSource is TextDocument doc)
{
return doc._rope;
}
return textSource.Text.ToCharArray();
}
#endregion
#region Text
private void ThrowIfRangeInvalid(int offset, int length)
{
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
if (length < 0 || offset + length > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
}
/// <inheritdoc/>
public string GetText(int offset, int length)
{
VerifyAccess();
return _rope.ToString(offset, length);
}
private void VerifyAccess()
{
Dispatcher.UIThread.VerifyAccess();
}
/// <summary>
public void SetOwnerThread(Thread newOwner)
{
// We need to lock here to ensure that in the null owner case,
// only one thread succeeds in taking ownership.
lock (_lockObject) {
if (ownerThread != null) {
VerifyAccess();
}
ownerThread = newOwner;
}
}
private void VerifyAccess()
{
if(Thread.CurrentThread != ownerThread)
{
throw new InvalidOperationException("Call from invalid thread.");
}
}
/// <summary>
/// Retrieves the text for a portion of the document.
/// </summary>
public string GetText(ISegment segment)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
return GetText(segment.Offset, segment.Length);
}
/// <inheritdoc/>
public int IndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.IndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int LastIndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.LastIndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int IndexOfAny(char[] anyOf, int startIndex, int count)
{
DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds
return _rope.IndexOfAny(anyOf, startIndex, count);
}
/// <inheritdoc/>
public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.IndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.LastIndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public char GetCharAt(int offset)
{
DebugVerifyAccess(); // frequently called, so must be fast in release builds
return _rope[offset];
}
private WeakReference _cachedText;
/// <summary>
/// Gets/Sets the text of the whole document.
/// </summary>
public string Text
{
get
{
VerifyAccess();
var completeText = _cachedText?.Target as string;
if (completeText == null)
{
completeText = _rope.ToString();
_cachedText = new WeakReference(completeText);
}
return completeText;
}
set
{
VerifyAccess();
if (value == null)
throw new ArgumentNullException(nameof(value));
Replace(0, _rope.Length, value);
}
}
/// <summary>
/// This event is called after a group of changes is completed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextChanged;
event EventHandler IDocument.ChangeCompleted
{
add => TextChanged += value;
remove => TextChanged -= value;
}
/// <inheritdoc/>
public int TextLength
{
get
{
VerifyAccess();
return _rope.Length;
}
}
/// <summary>
/// Is raised when the TextLength property changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextLengthChanged;
/// <summary>
/// Is raised before the document changes.
/// </summary>
/// <remarks>
/// <para>Here is the order in which events are raised during a document update:</para>
/// <list type="bullet">
/// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description>Start of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateStarted"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="Changing"/> event is raised</description></item>
/// <item><description>The document is changed</description></item>
/// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were
/// in the deleted text portion</description></item>
/// <item><description><see cref="Changed"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="TextChanged"/> event is raised</description></item>
/// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item>
/// <item><description>End of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateFinished"/> event is raised</description></item>
/// </list></item>
/// </list>
/// <para>
/// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>,
/// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>.
/// </para><para>
/// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls.
/// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done.
/// </para><para>
/// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step.
/// </para>
/// </remarks>
public event EventHandler<DocumentChangeEventArgs> Changing;
// Unfortunately EventHandler<T> is invariant, so we have to use two separate events
private event EventHandler<TextChangeEventArgs> TextChangingInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanging
{
add => TextChangingInternal += value;
remove => TextChangingInternal -= value;
}
/// <summary>
/// Is raised after the document has changed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler<DocumentChangeEventArgs> Changed;
private event EventHandler<TextChangeEventArgs> TextChangedInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanged
{
add => TextChangedInternal += value;
remove => TextChangedInternal -= value;
}
/// <summary>
/// Creates a snapshot of the current text.
/// </summary>
/// <remarks>
/// <para>This method returns an immutable snapshot of the document, and may be safely called even when
/// the document's owner thread is concurrently modifying the document.
/// </para><para>
/// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other
/// classes implementing ITextSource.CreateSnapshot().
/// </para><para>
/// </para>
/// </remarks>
public ITextSource CreateSnapshot()
{
lock (_lockObject)
{
return new RopeTextSource(_rope, _versionProvider.CurrentVersion);
}
}
/// <summary>
/// Creates a snapshot of a part of the current text.
/// </summary>
/// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks>
public ITextSource CreateSnapshot(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextSource(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public ITextSourceVersion Version => _versionProvider.CurrentVersion;
/// <inheritdoc/>
public TextReader CreateReader()
{
lock (_lockObject)
{
return new RopeTextReader(_rope);
}
}
/// <inheritdoc/>
public TextReader CreateReader(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextReader(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer)
{
VerifyAccess();
_rope.WriteTo(writer, 0, _rope.Length);
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer, int offset, int length)
{
VerifyAccess();
_rope.WriteTo(writer, offset, length);
}
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region BeginUpdate / EndUpdate
private int _beginUpdateCount;
/// <summary>
/// Gets if an update is running.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public bool IsInUpdate
{
get
{
VerifyAccess();
return _beginUpdateCount > 0;
}
}
/// <summary>
/// Immediately calls <see cref="BeginUpdate()"/>,
/// and returns an IDisposable that calls <see cref="EndUpdate()"/>.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public IDisposable RunUpdate()
{
BeginUpdate();
return new CallbackOnDispose(EndUpdate);
}
/// <summary>
/// <para>Begins a group of document changes.</para>
/// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will
/// group all changes into a single action.</para>
/// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number
/// of EndUpdate calls the events resume their work.</para>
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void BeginUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot change document within another document change.");
_beginUpdateCount++;
if (_beginUpdateCount == 1)
{
_undoStack.StartUndoGroup();
UpdateStarted?.Invoke(this, EventArgs.Empty);
}
}
/// <summary>
/// Ends a group of document changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void EndUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot end update within document change.");
if (_beginUpdateCount == 0)
throw new InvalidOperationException("No update is active.");
if (_beginUpdateCount == 1)
{
// fire change events inside the change group - event handlers might add additional
// document changes to the change group
FireChangeEvents();
_undoStack.EndUndoGroup();
_beginUpdateCount = 0;
UpdateFinished?.Invoke(this, EventArgs.Empty);
}
else
{
_beginUpdateCount -= 1;
}
}
/// <summary>
/// Occurs when a document change starts.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateStarted;
/// <summary>
/// Occurs when a document change is finished.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateFinished;
void IDocument.StartUndoableAction()
{
BeginUpdate();
}
void IDocument.EndUndoableAction()
{
EndUpdate();
}
IDisposable IDocument.OpenUndoGroup()
{
return RunUpdate();
}
#endregion
#region Fire events after update
private int _oldTextLength;
private int _oldLineCount;
private bool _fireTextChanged;
/// <summary>
/// Fires TextChanged, TextLengthChanged, LineCountChanged if required.
/// </summary>
internal void FireChangeEvents()
{
// it may be necessary to fire the event multiple times if the document is changed
// from inside the event handlers
while (_fireTextChanged)
{
_fireTextChanged = false;
TextChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("Text");
var textLength = _rope.Length;
if (textLength != _oldTextLength)
{
_oldTextLength = textLength;
TextLengthChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("TextLength");
}
var lineCount = _lineTree.LineCount;
if (lineCount != _oldLineCount)
{
_oldLineCount = lineCount;
LineCountChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("LineCount");
}
}
}
#endregion
#region Insert / Remove / Replace
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, string text)
{
Replace(offset, 0, new StringTextSource(text), null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, ITextSource text)
{
Replace(offset, 0, text, null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, new StringTextSource(text), null);
}
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, text, null);
}
}
/// <summary>
/// Removes text.
/// </summary>
public void Remove(ISegment segment)
{
Replace(segment, string.Empty);
}
/// <summary>
/// Removes text.
/// </summary>
/// <param name="offset">Starting offset of the text to be removed.</param>
/// <param name="length">Length of the text to be removed.</param>
public void Remove(int offset, int length)
{
Replace(offset, length, StringTextSource.Empty);
}
internal bool InDocumentChanging;
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, string text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, ITextSource text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, string text)
{
Replace(offset, length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, ITextSource text)
{
Replace(offset, length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMappingType);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType)
{
if (text == null)
throw new ArgumentNullException(nameof(text));
// Please see OffsetChangeMappingType XML comments for details on how these modes work.
switch (offsetChangeMappingType)
{
case OffsetChangeMappingType.Normal:
Replace(offset, length, text, null);
break;
case OffsetChangeMappingType.KeepAnchorBeforeInsertion:
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(
new OffsetChangeMapEntry(offset, length, text.TextLength, false, true)));
break;
case OffsetChangeMappingType.RemoveAndInsert:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else
{
var map = new OffsetChangeMap(2)
{
new OffsetChangeMapEntry(offset, length, 0),
new OffsetChangeMapEntry(offset, 0, text.TextLength)
};
map.Freeze();
Replace(offset, length, text, map);
}
break;
case OffsetChangeMappingType.CharacterReplace:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else if (text.TextLength > length)
{
// look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace
// the last character
var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else if (text.TextLength < length)
{
var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else
{
Replace(offset, length, text, OffsetChangeMap.Empty);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value");
}
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMap);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap)
{
text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text));
offsetChangeMap?.Freeze();
// Ensure that all changes take place inside an update group.
// Will also take care of throwing an exception if inDocumentChanging is set.
BeginUpdate();
try
{
// protect document change against corruption by other changes inside the event handlers
InDocumentChanging = true;
try
{
// The range verification must wait until after the BeginUpdate() call because the document
// might be modified inside the UpdateStarted event.
ThrowIfRangeInvalid(offset, length);
DoReplace(offset, length, text, offsetChangeMap);
}
finally
{
InDocumentChanging = false;
}
}
finally
{
EndUpdate();
}
}
private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap)
{
if (length == 0 && newText.TextLength == 0)
return;
// trying to replace a single character in 'Normal' mode?
// for single characters, 'CharacterReplace' mode is equivalent, but more performant
// (we don't have to touch the anchorTree at all in 'CharacterReplace' mode)
if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null)
offsetChangeMap = OffsetChangeMap.Empty;
ITextSource removedText;
if (length == 0)
{
removedText = StringTextSource.Empty;
}
else if (length < 100)
{
removedText = new StringTextSource(_rope.ToString(offset, length));
}
else
{
// use a rope if the removed string is long
removedText = new RopeTextSource(_rope.GetRange(offset, length));
}
var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap);
// fire DocumentChanging event
Changing?.Invoke(this, args);
TextChangingInternal?.Invoke(this, args);
_undoStack.Push(this, args);
_cachedText = null; // reset cache of complete document text
_fireTextChanged = true;
var delayedEvents = new DelayedEvents();
lock (_lockObject)
{
// create linked list of checkpoints
_versionProvider.AppendChange(args);
// now update the textBuffer and lineTree
if (offset == 0 && length == _rope.Length)
{
// optimize replacing the whole document
_rope.Clear();
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(0, newRopeTextSource.GetRope());
else
_rope.InsertText(0, newText.Text);
_lineManager.Rebuild();
}
else
{
_rope.RemoveRange(offset, length);
_lineManager.Remove(offset, length);
#if DEBUG
_lineTree.CheckProperties();
#endif
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(offset, newRopeTextSource.GetRope());
else
_rope.InsertText(offset, newText.Text);
_lineManager.Insert(offset, newText);
#if DEBUG
_lineTree.CheckProperties();
#endif
}
}
// update text anchors
if (offsetChangeMap == null)
{
_anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents);
}
else
{
foreach (var entry in offsetChangeMap)
{
_anchorTree.HandleTextChange(entry, delayedEvents);
}
}
_lineManager.ChangeComplete(args);
// raise delayed events after our data structures are consistent again
delayedEvents.RaiseEvents();
// fire DocumentChanged event
Changed?.Invoke(this, args);
TextChangedInternal?.Invoke(this, args);
}
#endregion
#region GetLineBy...
/// <summary>
/// Gets a read-only list of lines.
/// </summary>
/// <remarks><inheritdoc cref="DocumentLine"/></remarks>
public IList<DocumentLine> Lines => _lineTree;
/// <summary>
/// Gets a line by the line number: O(log n)
/// </summary>
public DocumentLine GetLineByNumber(int number)
{
VerifyAccess();
if (number < 1 || number > _lineTree.LineCount)
throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount);
return _lineTree.GetByNumber(number);
}
IDocumentLine IDocument.GetLineByNumber(int lineNumber)
{
return GetLineByNumber(lineNumber);
}
/// <summary>
/// Gets a document lines by offset.
/// Runtime: O(log n)
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")]
public DocumentLine GetLineByOffset(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length);
}
return _lineTree.GetByOffset(offset);
}
IDocumentLine IDocument.GetLineByOffset(int offset)
{
return GetLineByOffset(offset);
}
#endregion
#region GetOffset / GetLocation
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(TextLocation location)
{
return GetOffset(location.Line, location.Column);
}
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(int line, int column)
{
var docLine = GetLineByNumber(line);
if (column <= 0)
return docLine.Offset;
if (column > docLine.Length)
return docLine.EndOffset;
return docLine.Offset + column - 1;
}
/// <summary>
/// Gets the location from an offset.
/// </summary>
/// <seealso cref="GetOffset(TextLocation)"/>
public TextLocation GetLocation(int offset)
{
var line = GetLineByOffset(offset);
return new TextLocation(line.LineNumber, offset - line.Offset + 1);
}
#endregion
#region Line Trackers
private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>();
/// <summary>
/// Gets the list of <see cref="ILineTracker"/>s attached to this document.
/// You can add custom line trackers to this list.
/// </summary>
public IList<ILineTracker> LineTrackers
{
get
{
VerifyAccess();
return _lineTrackers;
}
}
#endregion
#region UndoStack
public UndoStack _undoStack;
/// <summary>
/// Gets the <see cref="UndoStack"/> of the document.
/// </summary>
/// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks>
public UndoStack UndoStack
{
get => _undoStack;
set
{
if (value == null)
throw new ArgumentNullException();
if (value != _undoStack)
{
_undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document
// ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress)
_undoStack = value;
OnPropertyChanged("UndoStack");
}
}
}
#endregion
#region CreateAnchor
/// <summary>
/// Creates a new <see cref="TextAnchor"/> at the specified offset.
/// </summary>
/// <inheritdoc cref="TextAnchor" select="remarks|example"/>
public TextAnchor CreateAnchor(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
return _anchorTree.CreateAnchor(offset);
}
ITextAnchor IDocument.CreateAnchor(int offset)
{
return CreateAnchor(offset);
}
#endregion
#region LineCount
/// <summary>
/// Gets the total number of lines in the document.
/// Runtime: O(1).
/// </summary>
public int LineCount
{
get
{
VerifyAccess();
return _lineTree.LineCount;
}
}
/// <summary>
/// Is raised when the LineCount property changes.
/// </summary>
public event EventHandler LineCountChanged;
#endregion
#region Debugging
[Conditional("DEBUG")]
internal void DebugVerifyAccess()
{
VerifyAccess();
}
/// <summary>
/// Gets the document lines tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetLineTreeAsString()
{
#if DEBUG
return _lineTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
/// <summary>
/// Gets the text anchor tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetTextAnchorTreeAsString()
{
#if DEBUG
return _anchorTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
#endregion
#region Service Provider
private IServiceProvider _serviceProvider;
internal IServiceProvider ServiceProvider
{
get
{
VerifyAccess();
if (_serviceProvider == null)
{
var container = new ServiceContainer();
container.AddService(this);
container.AddService<IDocument>(this);
_serviceProvider = container;
}
return _serviceProvider;
}
set
{
VerifyAccess();
_serviceProvider = value ?? throw new ArgumentNullException(nameof(value));
}
}
object IServiceProvider.GetService(Type serviceType)
{
return ServiceProvider.GetService(serviceType);
}
#endregion
#region FileName
private string _fileName;
/// <inheritdoc/>
public event EventHandler FileNameChanged;
private void OnFileNameChanged(EventArgs e)
{
FileNameChanged?.Invoke(this, e);
}
/// <inheritdoc/>
public string FileName
{
get { return _fileName; }
set
{
if (_fileName != value)
{
_fileName = value;
OnFileNameChanged(EventArgs.Empty);
}
}
}
#endregion
}
}
<MSG> Merge pull request #51 from danwalmsley/fix-thread-verification
verify access checks against thread textdocument is created on.
<DFF> @@ -26,6 +26,7 @@ using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
+using System.Threading;
namespace AvaloniaEdit.Document
{
@@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document
return _rope.ToString(offset, length);
}
+ private Thread ownerThread = Thread.CurrentThread;
+
private void VerifyAccess()
{
- Dispatcher.UIThread.VerifyAccess();
+ if(Thread.CurrentThread != ownerThread)
+ {
+ throw new InvalidOperationException("Call from invalid thread.");
+ }
}
/// <summary>
| 7 | Merge pull request #51 from danwalmsley/fix-thread-verification | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059870 | <NME> TextDocument.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
namespace AvaloniaEdit.Document
{
/// <summary>
/// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events.
/// </summary>
/// <remarks>
/// <b>Thread safety:</b>
/// <inheritdoc cref="VerifyAccess"/>
/// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para>
/// </remarks>
public sealed class TextDocument : IDocument, INotifyPropertyChanged
{
#region Thread ownership
private readonly object _lockObject = new object();
#endregion
#region Fields + Constructor
private readonly Rope<char> _rope;
private readonly DocumentLineTree _lineTree;
private readonly LineManager _lineManager;
private readonly TextAnchorTree _anchorTree;
private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider();
/// <summary>
/// Create an empty text document.
/// </summary>
public TextDocument()
: this(string.Empty.ToCharArray())
{
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(IEnumerable<char> initialText)
{
if (initialText == null)
throw new ArgumentNullException(nameof(initialText));
_rope = new Rope<char>(initialText);
_lineTree = new DocumentLineTree(this);
_lineManager = new LineManager(_lineTree, this);
_lineTrackers.CollectionChanged += delegate
{
_lineManager.UpdateListOfLineTrackers();
};
_anchorTree = new TextAnchorTree(this);
_undoStack = new UndoStack();
FireChangeEvents();
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(ITextSource initialText)
: this(GetTextFromTextSource(initialText))
{
}
// gets the text from a text source, directly retrieving the underlying rope where possible
private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource)
{
if (textSource == null)
throw new ArgumentNullException(nameof(textSource));
if (textSource is RopeTextSource rts)
{
return rts.GetRope();
}
if (textSource is TextDocument doc)
{
return doc._rope;
}
return textSource.Text.ToCharArray();
}
#endregion
#region Text
private void ThrowIfRangeInvalid(int offset, int length)
{
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
if (length < 0 || offset + length > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
}
/// <inheritdoc/>
public string GetText(int offset, int length)
{
VerifyAccess();
return _rope.ToString(offset, length);
}
private void VerifyAccess()
{
Dispatcher.UIThread.VerifyAccess();
}
/// <summary>
public void SetOwnerThread(Thread newOwner)
{
// We need to lock here to ensure that in the null owner case,
// only one thread succeeds in taking ownership.
lock (_lockObject) {
if (ownerThread != null) {
VerifyAccess();
}
ownerThread = newOwner;
}
}
private void VerifyAccess()
{
if(Thread.CurrentThread != ownerThread)
{
throw new InvalidOperationException("Call from invalid thread.");
}
}
/// <summary>
/// Retrieves the text for a portion of the document.
/// </summary>
public string GetText(ISegment segment)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
return GetText(segment.Offset, segment.Length);
}
/// <inheritdoc/>
public int IndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.IndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int LastIndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.LastIndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int IndexOfAny(char[] anyOf, int startIndex, int count)
{
DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds
return _rope.IndexOfAny(anyOf, startIndex, count);
}
/// <inheritdoc/>
public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.IndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.LastIndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public char GetCharAt(int offset)
{
DebugVerifyAccess(); // frequently called, so must be fast in release builds
return _rope[offset];
}
private WeakReference _cachedText;
/// <summary>
/// Gets/Sets the text of the whole document.
/// </summary>
public string Text
{
get
{
VerifyAccess();
var completeText = _cachedText?.Target as string;
if (completeText == null)
{
completeText = _rope.ToString();
_cachedText = new WeakReference(completeText);
}
return completeText;
}
set
{
VerifyAccess();
if (value == null)
throw new ArgumentNullException(nameof(value));
Replace(0, _rope.Length, value);
}
}
/// <summary>
/// This event is called after a group of changes is completed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextChanged;
event EventHandler IDocument.ChangeCompleted
{
add => TextChanged += value;
remove => TextChanged -= value;
}
/// <inheritdoc/>
public int TextLength
{
get
{
VerifyAccess();
return _rope.Length;
}
}
/// <summary>
/// Is raised when the TextLength property changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextLengthChanged;
/// <summary>
/// Is raised before the document changes.
/// </summary>
/// <remarks>
/// <para>Here is the order in which events are raised during a document update:</para>
/// <list type="bullet">
/// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description>Start of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateStarted"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="Changing"/> event is raised</description></item>
/// <item><description>The document is changed</description></item>
/// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were
/// in the deleted text portion</description></item>
/// <item><description><see cref="Changed"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="TextChanged"/> event is raised</description></item>
/// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item>
/// <item><description>End of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateFinished"/> event is raised</description></item>
/// </list></item>
/// </list>
/// <para>
/// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>,
/// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>.
/// </para><para>
/// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls.
/// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done.
/// </para><para>
/// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step.
/// </para>
/// </remarks>
public event EventHandler<DocumentChangeEventArgs> Changing;
// Unfortunately EventHandler<T> is invariant, so we have to use two separate events
private event EventHandler<TextChangeEventArgs> TextChangingInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanging
{
add => TextChangingInternal += value;
remove => TextChangingInternal -= value;
}
/// <summary>
/// Is raised after the document has changed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler<DocumentChangeEventArgs> Changed;
private event EventHandler<TextChangeEventArgs> TextChangedInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanged
{
add => TextChangedInternal += value;
remove => TextChangedInternal -= value;
}
/// <summary>
/// Creates a snapshot of the current text.
/// </summary>
/// <remarks>
/// <para>This method returns an immutable snapshot of the document, and may be safely called even when
/// the document's owner thread is concurrently modifying the document.
/// </para><para>
/// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other
/// classes implementing ITextSource.CreateSnapshot().
/// </para><para>
/// </para>
/// </remarks>
public ITextSource CreateSnapshot()
{
lock (_lockObject)
{
return new RopeTextSource(_rope, _versionProvider.CurrentVersion);
}
}
/// <summary>
/// Creates a snapshot of a part of the current text.
/// </summary>
/// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks>
public ITextSource CreateSnapshot(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextSource(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public ITextSourceVersion Version => _versionProvider.CurrentVersion;
/// <inheritdoc/>
public TextReader CreateReader()
{
lock (_lockObject)
{
return new RopeTextReader(_rope);
}
}
/// <inheritdoc/>
public TextReader CreateReader(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextReader(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer)
{
VerifyAccess();
_rope.WriteTo(writer, 0, _rope.Length);
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer, int offset, int length)
{
VerifyAccess();
_rope.WriteTo(writer, offset, length);
}
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region BeginUpdate / EndUpdate
private int _beginUpdateCount;
/// <summary>
/// Gets if an update is running.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public bool IsInUpdate
{
get
{
VerifyAccess();
return _beginUpdateCount > 0;
}
}
/// <summary>
/// Immediately calls <see cref="BeginUpdate()"/>,
/// and returns an IDisposable that calls <see cref="EndUpdate()"/>.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public IDisposable RunUpdate()
{
BeginUpdate();
return new CallbackOnDispose(EndUpdate);
}
/// <summary>
/// <para>Begins a group of document changes.</para>
/// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will
/// group all changes into a single action.</para>
/// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number
/// of EndUpdate calls the events resume their work.</para>
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void BeginUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot change document within another document change.");
_beginUpdateCount++;
if (_beginUpdateCount == 1)
{
_undoStack.StartUndoGroup();
UpdateStarted?.Invoke(this, EventArgs.Empty);
}
}
/// <summary>
/// Ends a group of document changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void EndUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot end update within document change.");
if (_beginUpdateCount == 0)
throw new InvalidOperationException("No update is active.");
if (_beginUpdateCount == 1)
{
// fire change events inside the change group - event handlers might add additional
// document changes to the change group
FireChangeEvents();
_undoStack.EndUndoGroup();
_beginUpdateCount = 0;
UpdateFinished?.Invoke(this, EventArgs.Empty);
}
else
{
_beginUpdateCount -= 1;
}
}
/// <summary>
/// Occurs when a document change starts.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateStarted;
/// <summary>
/// Occurs when a document change is finished.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateFinished;
void IDocument.StartUndoableAction()
{
BeginUpdate();
}
void IDocument.EndUndoableAction()
{
EndUpdate();
}
IDisposable IDocument.OpenUndoGroup()
{
return RunUpdate();
}
#endregion
#region Fire events after update
private int _oldTextLength;
private int _oldLineCount;
private bool _fireTextChanged;
/// <summary>
/// Fires TextChanged, TextLengthChanged, LineCountChanged if required.
/// </summary>
internal void FireChangeEvents()
{
// it may be necessary to fire the event multiple times if the document is changed
// from inside the event handlers
while (_fireTextChanged)
{
_fireTextChanged = false;
TextChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("Text");
var textLength = _rope.Length;
if (textLength != _oldTextLength)
{
_oldTextLength = textLength;
TextLengthChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("TextLength");
}
var lineCount = _lineTree.LineCount;
if (lineCount != _oldLineCount)
{
_oldLineCount = lineCount;
LineCountChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("LineCount");
}
}
}
#endregion
#region Insert / Remove / Replace
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, string text)
{
Replace(offset, 0, new StringTextSource(text), null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, ITextSource text)
{
Replace(offset, 0, text, null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, new StringTextSource(text), null);
}
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, text, null);
}
}
/// <summary>
/// Removes text.
/// </summary>
public void Remove(ISegment segment)
{
Replace(segment, string.Empty);
}
/// <summary>
/// Removes text.
/// </summary>
/// <param name="offset">Starting offset of the text to be removed.</param>
/// <param name="length">Length of the text to be removed.</param>
public void Remove(int offset, int length)
{
Replace(offset, length, StringTextSource.Empty);
}
internal bool InDocumentChanging;
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, string text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, ITextSource text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, string text)
{
Replace(offset, length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, ITextSource text)
{
Replace(offset, length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMappingType);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType)
{
if (text == null)
throw new ArgumentNullException(nameof(text));
// Please see OffsetChangeMappingType XML comments for details on how these modes work.
switch (offsetChangeMappingType)
{
case OffsetChangeMappingType.Normal:
Replace(offset, length, text, null);
break;
case OffsetChangeMappingType.KeepAnchorBeforeInsertion:
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(
new OffsetChangeMapEntry(offset, length, text.TextLength, false, true)));
break;
case OffsetChangeMappingType.RemoveAndInsert:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else
{
var map = new OffsetChangeMap(2)
{
new OffsetChangeMapEntry(offset, length, 0),
new OffsetChangeMapEntry(offset, 0, text.TextLength)
};
map.Freeze();
Replace(offset, length, text, map);
}
break;
case OffsetChangeMappingType.CharacterReplace:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else if (text.TextLength > length)
{
// look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace
// the last character
var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else if (text.TextLength < length)
{
var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else
{
Replace(offset, length, text, OffsetChangeMap.Empty);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value");
}
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMap);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap)
{
text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text));
offsetChangeMap?.Freeze();
// Ensure that all changes take place inside an update group.
// Will also take care of throwing an exception if inDocumentChanging is set.
BeginUpdate();
try
{
// protect document change against corruption by other changes inside the event handlers
InDocumentChanging = true;
try
{
// The range verification must wait until after the BeginUpdate() call because the document
// might be modified inside the UpdateStarted event.
ThrowIfRangeInvalid(offset, length);
DoReplace(offset, length, text, offsetChangeMap);
}
finally
{
InDocumentChanging = false;
}
}
finally
{
EndUpdate();
}
}
private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap)
{
if (length == 0 && newText.TextLength == 0)
return;
// trying to replace a single character in 'Normal' mode?
// for single characters, 'CharacterReplace' mode is equivalent, but more performant
// (we don't have to touch the anchorTree at all in 'CharacterReplace' mode)
if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null)
offsetChangeMap = OffsetChangeMap.Empty;
ITextSource removedText;
if (length == 0)
{
removedText = StringTextSource.Empty;
}
else if (length < 100)
{
removedText = new StringTextSource(_rope.ToString(offset, length));
}
else
{
// use a rope if the removed string is long
removedText = new RopeTextSource(_rope.GetRange(offset, length));
}
var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap);
// fire DocumentChanging event
Changing?.Invoke(this, args);
TextChangingInternal?.Invoke(this, args);
_undoStack.Push(this, args);
_cachedText = null; // reset cache of complete document text
_fireTextChanged = true;
var delayedEvents = new DelayedEvents();
lock (_lockObject)
{
// create linked list of checkpoints
_versionProvider.AppendChange(args);
// now update the textBuffer and lineTree
if (offset == 0 && length == _rope.Length)
{
// optimize replacing the whole document
_rope.Clear();
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(0, newRopeTextSource.GetRope());
else
_rope.InsertText(0, newText.Text);
_lineManager.Rebuild();
}
else
{
_rope.RemoveRange(offset, length);
_lineManager.Remove(offset, length);
#if DEBUG
_lineTree.CheckProperties();
#endif
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(offset, newRopeTextSource.GetRope());
else
_rope.InsertText(offset, newText.Text);
_lineManager.Insert(offset, newText);
#if DEBUG
_lineTree.CheckProperties();
#endif
}
}
// update text anchors
if (offsetChangeMap == null)
{
_anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents);
}
else
{
foreach (var entry in offsetChangeMap)
{
_anchorTree.HandleTextChange(entry, delayedEvents);
}
}
_lineManager.ChangeComplete(args);
// raise delayed events after our data structures are consistent again
delayedEvents.RaiseEvents();
// fire DocumentChanged event
Changed?.Invoke(this, args);
TextChangedInternal?.Invoke(this, args);
}
#endregion
#region GetLineBy...
/// <summary>
/// Gets a read-only list of lines.
/// </summary>
/// <remarks><inheritdoc cref="DocumentLine"/></remarks>
public IList<DocumentLine> Lines => _lineTree;
/// <summary>
/// Gets a line by the line number: O(log n)
/// </summary>
public DocumentLine GetLineByNumber(int number)
{
VerifyAccess();
if (number < 1 || number > _lineTree.LineCount)
throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount);
return _lineTree.GetByNumber(number);
}
IDocumentLine IDocument.GetLineByNumber(int lineNumber)
{
return GetLineByNumber(lineNumber);
}
/// <summary>
/// Gets a document lines by offset.
/// Runtime: O(log n)
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")]
public DocumentLine GetLineByOffset(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length);
}
return _lineTree.GetByOffset(offset);
}
IDocumentLine IDocument.GetLineByOffset(int offset)
{
return GetLineByOffset(offset);
}
#endregion
#region GetOffset / GetLocation
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(TextLocation location)
{
return GetOffset(location.Line, location.Column);
}
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(int line, int column)
{
var docLine = GetLineByNumber(line);
if (column <= 0)
return docLine.Offset;
if (column > docLine.Length)
return docLine.EndOffset;
return docLine.Offset + column - 1;
}
/// <summary>
/// Gets the location from an offset.
/// </summary>
/// <seealso cref="GetOffset(TextLocation)"/>
public TextLocation GetLocation(int offset)
{
var line = GetLineByOffset(offset);
return new TextLocation(line.LineNumber, offset - line.Offset + 1);
}
#endregion
#region Line Trackers
private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>();
/// <summary>
/// Gets the list of <see cref="ILineTracker"/>s attached to this document.
/// You can add custom line trackers to this list.
/// </summary>
public IList<ILineTracker> LineTrackers
{
get
{
VerifyAccess();
return _lineTrackers;
}
}
#endregion
#region UndoStack
public UndoStack _undoStack;
/// <summary>
/// Gets the <see cref="UndoStack"/> of the document.
/// </summary>
/// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks>
public UndoStack UndoStack
{
get => _undoStack;
set
{
if (value == null)
throw new ArgumentNullException();
if (value != _undoStack)
{
_undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document
// ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress)
_undoStack = value;
OnPropertyChanged("UndoStack");
}
}
}
#endregion
#region CreateAnchor
/// <summary>
/// Creates a new <see cref="TextAnchor"/> at the specified offset.
/// </summary>
/// <inheritdoc cref="TextAnchor" select="remarks|example"/>
public TextAnchor CreateAnchor(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
return _anchorTree.CreateAnchor(offset);
}
ITextAnchor IDocument.CreateAnchor(int offset)
{
return CreateAnchor(offset);
}
#endregion
#region LineCount
/// <summary>
/// Gets the total number of lines in the document.
/// Runtime: O(1).
/// </summary>
public int LineCount
{
get
{
VerifyAccess();
return _lineTree.LineCount;
}
}
/// <summary>
/// Is raised when the LineCount property changes.
/// </summary>
public event EventHandler LineCountChanged;
#endregion
#region Debugging
[Conditional("DEBUG")]
internal void DebugVerifyAccess()
{
VerifyAccess();
}
/// <summary>
/// Gets the document lines tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetLineTreeAsString()
{
#if DEBUG
return _lineTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
/// <summary>
/// Gets the text anchor tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetTextAnchorTreeAsString()
{
#if DEBUG
return _anchorTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
#endregion
#region Service Provider
private IServiceProvider _serviceProvider;
internal IServiceProvider ServiceProvider
{
get
{
VerifyAccess();
if (_serviceProvider == null)
{
var container = new ServiceContainer();
container.AddService(this);
container.AddService<IDocument>(this);
_serviceProvider = container;
}
return _serviceProvider;
}
set
{
VerifyAccess();
_serviceProvider = value ?? throw new ArgumentNullException(nameof(value));
}
}
object IServiceProvider.GetService(Type serviceType)
{
return ServiceProvider.GetService(serviceType);
}
#endregion
#region FileName
private string _fileName;
/// <inheritdoc/>
public event EventHandler FileNameChanged;
private void OnFileNameChanged(EventArgs e)
{
FileNameChanged?.Invoke(this, e);
}
/// <inheritdoc/>
public string FileName
{
get { return _fileName; }
set
{
if (_fileName != value)
{
_fileName = value;
OnFileNameChanged(EventArgs.Empty);
}
}
}
#endregion
}
}
<MSG> Merge pull request #51 from danwalmsley/fix-thread-verification
verify access checks against thread textdocument is created on.
<DFF> @@ -26,6 +26,7 @@ using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
+using System.Threading;
namespace AvaloniaEdit.Document
{
@@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document
return _rope.ToString(offset, length);
}
+ private Thread ownerThread = Thread.CurrentThread;
+
private void VerifyAccess()
{
- Dispatcher.UIThread.VerifyAccess();
+ if(Thread.CurrentThread != ownerThread)
+ {
+ throw new InvalidOperationException("Call from invalid thread.");
+ }
}
/// <summary>
| 7 | Merge pull request #51 from danwalmsley/fix-thread-verification | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059871 | <NME> TextDocument.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
namespace AvaloniaEdit.Document
{
/// <summary>
/// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events.
/// </summary>
/// <remarks>
/// <b>Thread safety:</b>
/// <inheritdoc cref="VerifyAccess"/>
/// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para>
/// </remarks>
public sealed class TextDocument : IDocument, INotifyPropertyChanged
{
#region Thread ownership
private readonly object _lockObject = new object();
#endregion
#region Fields + Constructor
private readonly Rope<char> _rope;
private readonly DocumentLineTree _lineTree;
private readonly LineManager _lineManager;
private readonly TextAnchorTree _anchorTree;
private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider();
/// <summary>
/// Create an empty text document.
/// </summary>
public TextDocument()
: this(string.Empty.ToCharArray())
{
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(IEnumerable<char> initialText)
{
if (initialText == null)
throw new ArgumentNullException(nameof(initialText));
_rope = new Rope<char>(initialText);
_lineTree = new DocumentLineTree(this);
_lineManager = new LineManager(_lineTree, this);
_lineTrackers.CollectionChanged += delegate
{
_lineManager.UpdateListOfLineTrackers();
};
_anchorTree = new TextAnchorTree(this);
_undoStack = new UndoStack();
FireChangeEvents();
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(ITextSource initialText)
: this(GetTextFromTextSource(initialText))
{
}
// gets the text from a text source, directly retrieving the underlying rope where possible
private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource)
{
if (textSource == null)
throw new ArgumentNullException(nameof(textSource));
if (textSource is RopeTextSource rts)
{
return rts.GetRope();
}
if (textSource is TextDocument doc)
{
return doc._rope;
}
return textSource.Text.ToCharArray();
}
#endregion
#region Text
private void ThrowIfRangeInvalid(int offset, int length)
{
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
if (length < 0 || offset + length > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
}
/// <inheritdoc/>
public string GetText(int offset, int length)
{
VerifyAccess();
return _rope.ToString(offset, length);
}
private void VerifyAccess()
{
Dispatcher.UIThread.VerifyAccess();
}
/// <summary>
public void SetOwnerThread(Thread newOwner)
{
// We need to lock here to ensure that in the null owner case,
// only one thread succeeds in taking ownership.
lock (_lockObject) {
if (ownerThread != null) {
VerifyAccess();
}
ownerThread = newOwner;
}
}
private void VerifyAccess()
{
if(Thread.CurrentThread != ownerThread)
{
throw new InvalidOperationException("Call from invalid thread.");
}
}
/// <summary>
/// Retrieves the text for a portion of the document.
/// </summary>
public string GetText(ISegment segment)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
return GetText(segment.Offset, segment.Length);
}
/// <inheritdoc/>
public int IndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.IndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int LastIndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.LastIndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int IndexOfAny(char[] anyOf, int startIndex, int count)
{
DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds
return _rope.IndexOfAny(anyOf, startIndex, count);
}
/// <inheritdoc/>
public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.IndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.LastIndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public char GetCharAt(int offset)
{
DebugVerifyAccess(); // frequently called, so must be fast in release builds
return _rope[offset];
}
private WeakReference _cachedText;
/// <summary>
/// Gets/Sets the text of the whole document.
/// </summary>
public string Text
{
get
{
VerifyAccess();
var completeText = _cachedText?.Target as string;
if (completeText == null)
{
completeText = _rope.ToString();
_cachedText = new WeakReference(completeText);
}
return completeText;
}
set
{
VerifyAccess();
if (value == null)
throw new ArgumentNullException(nameof(value));
Replace(0, _rope.Length, value);
}
}
/// <summary>
/// This event is called after a group of changes is completed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextChanged;
event EventHandler IDocument.ChangeCompleted
{
add => TextChanged += value;
remove => TextChanged -= value;
}
/// <inheritdoc/>
public int TextLength
{
get
{
VerifyAccess();
return _rope.Length;
}
}
/// <summary>
/// Is raised when the TextLength property changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextLengthChanged;
/// <summary>
/// Is raised before the document changes.
/// </summary>
/// <remarks>
/// <para>Here is the order in which events are raised during a document update:</para>
/// <list type="bullet">
/// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description>Start of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateStarted"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="Changing"/> event is raised</description></item>
/// <item><description>The document is changed</description></item>
/// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were
/// in the deleted text portion</description></item>
/// <item><description><see cref="Changed"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="TextChanged"/> event is raised</description></item>
/// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item>
/// <item><description>End of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateFinished"/> event is raised</description></item>
/// </list></item>
/// </list>
/// <para>
/// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>,
/// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>.
/// </para><para>
/// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls.
/// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done.
/// </para><para>
/// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step.
/// </para>
/// </remarks>
public event EventHandler<DocumentChangeEventArgs> Changing;
// Unfortunately EventHandler<T> is invariant, so we have to use two separate events
private event EventHandler<TextChangeEventArgs> TextChangingInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanging
{
add => TextChangingInternal += value;
remove => TextChangingInternal -= value;
}
/// <summary>
/// Is raised after the document has changed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler<DocumentChangeEventArgs> Changed;
private event EventHandler<TextChangeEventArgs> TextChangedInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanged
{
add => TextChangedInternal += value;
remove => TextChangedInternal -= value;
}
/// <summary>
/// Creates a snapshot of the current text.
/// </summary>
/// <remarks>
/// <para>This method returns an immutable snapshot of the document, and may be safely called even when
/// the document's owner thread is concurrently modifying the document.
/// </para><para>
/// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other
/// classes implementing ITextSource.CreateSnapshot().
/// </para><para>
/// </para>
/// </remarks>
public ITextSource CreateSnapshot()
{
lock (_lockObject)
{
return new RopeTextSource(_rope, _versionProvider.CurrentVersion);
}
}
/// <summary>
/// Creates a snapshot of a part of the current text.
/// </summary>
/// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks>
public ITextSource CreateSnapshot(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextSource(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public ITextSourceVersion Version => _versionProvider.CurrentVersion;
/// <inheritdoc/>
public TextReader CreateReader()
{
lock (_lockObject)
{
return new RopeTextReader(_rope);
}
}
/// <inheritdoc/>
public TextReader CreateReader(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextReader(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer)
{
VerifyAccess();
_rope.WriteTo(writer, 0, _rope.Length);
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer, int offset, int length)
{
VerifyAccess();
_rope.WriteTo(writer, offset, length);
}
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region BeginUpdate / EndUpdate
private int _beginUpdateCount;
/// <summary>
/// Gets if an update is running.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public bool IsInUpdate
{
get
{
VerifyAccess();
return _beginUpdateCount > 0;
}
}
/// <summary>
/// Immediately calls <see cref="BeginUpdate()"/>,
/// and returns an IDisposable that calls <see cref="EndUpdate()"/>.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public IDisposable RunUpdate()
{
BeginUpdate();
return new CallbackOnDispose(EndUpdate);
}
/// <summary>
/// <para>Begins a group of document changes.</para>
/// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will
/// group all changes into a single action.</para>
/// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number
/// of EndUpdate calls the events resume their work.</para>
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void BeginUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot change document within another document change.");
_beginUpdateCount++;
if (_beginUpdateCount == 1)
{
_undoStack.StartUndoGroup();
UpdateStarted?.Invoke(this, EventArgs.Empty);
}
}
/// <summary>
/// Ends a group of document changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void EndUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot end update within document change.");
if (_beginUpdateCount == 0)
throw new InvalidOperationException("No update is active.");
if (_beginUpdateCount == 1)
{
// fire change events inside the change group - event handlers might add additional
// document changes to the change group
FireChangeEvents();
_undoStack.EndUndoGroup();
_beginUpdateCount = 0;
UpdateFinished?.Invoke(this, EventArgs.Empty);
}
else
{
_beginUpdateCount -= 1;
}
}
/// <summary>
/// Occurs when a document change starts.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateStarted;
/// <summary>
/// Occurs when a document change is finished.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateFinished;
void IDocument.StartUndoableAction()
{
BeginUpdate();
}
void IDocument.EndUndoableAction()
{
EndUpdate();
}
IDisposable IDocument.OpenUndoGroup()
{
return RunUpdate();
}
#endregion
#region Fire events after update
private int _oldTextLength;
private int _oldLineCount;
private bool _fireTextChanged;
/// <summary>
/// Fires TextChanged, TextLengthChanged, LineCountChanged if required.
/// </summary>
internal void FireChangeEvents()
{
// it may be necessary to fire the event multiple times if the document is changed
// from inside the event handlers
while (_fireTextChanged)
{
_fireTextChanged = false;
TextChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("Text");
var textLength = _rope.Length;
if (textLength != _oldTextLength)
{
_oldTextLength = textLength;
TextLengthChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("TextLength");
}
var lineCount = _lineTree.LineCount;
if (lineCount != _oldLineCount)
{
_oldLineCount = lineCount;
LineCountChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("LineCount");
}
}
}
#endregion
#region Insert / Remove / Replace
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, string text)
{
Replace(offset, 0, new StringTextSource(text), null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, ITextSource text)
{
Replace(offset, 0, text, null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, new StringTextSource(text), null);
}
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, text, null);
}
}
/// <summary>
/// Removes text.
/// </summary>
public void Remove(ISegment segment)
{
Replace(segment, string.Empty);
}
/// <summary>
/// Removes text.
/// </summary>
/// <param name="offset">Starting offset of the text to be removed.</param>
/// <param name="length">Length of the text to be removed.</param>
public void Remove(int offset, int length)
{
Replace(offset, length, StringTextSource.Empty);
}
internal bool InDocumentChanging;
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, string text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, ITextSource text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, string text)
{
Replace(offset, length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, ITextSource text)
{
Replace(offset, length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMappingType);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType)
{
if (text == null)
throw new ArgumentNullException(nameof(text));
// Please see OffsetChangeMappingType XML comments for details on how these modes work.
switch (offsetChangeMappingType)
{
case OffsetChangeMappingType.Normal:
Replace(offset, length, text, null);
break;
case OffsetChangeMappingType.KeepAnchorBeforeInsertion:
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(
new OffsetChangeMapEntry(offset, length, text.TextLength, false, true)));
break;
case OffsetChangeMappingType.RemoveAndInsert:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else
{
var map = new OffsetChangeMap(2)
{
new OffsetChangeMapEntry(offset, length, 0),
new OffsetChangeMapEntry(offset, 0, text.TextLength)
};
map.Freeze();
Replace(offset, length, text, map);
}
break;
case OffsetChangeMappingType.CharacterReplace:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else if (text.TextLength > length)
{
// look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace
// the last character
var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else if (text.TextLength < length)
{
var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else
{
Replace(offset, length, text, OffsetChangeMap.Empty);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value");
}
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMap);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap)
{
text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text));
offsetChangeMap?.Freeze();
// Ensure that all changes take place inside an update group.
// Will also take care of throwing an exception if inDocumentChanging is set.
BeginUpdate();
try
{
// protect document change against corruption by other changes inside the event handlers
InDocumentChanging = true;
try
{
// The range verification must wait until after the BeginUpdate() call because the document
// might be modified inside the UpdateStarted event.
ThrowIfRangeInvalid(offset, length);
DoReplace(offset, length, text, offsetChangeMap);
}
finally
{
InDocumentChanging = false;
}
}
finally
{
EndUpdate();
}
}
private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap)
{
if (length == 0 && newText.TextLength == 0)
return;
// trying to replace a single character in 'Normal' mode?
// for single characters, 'CharacterReplace' mode is equivalent, but more performant
// (we don't have to touch the anchorTree at all in 'CharacterReplace' mode)
if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null)
offsetChangeMap = OffsetChangeMap.Empty;
ITextSource removedText;
if (length == 0)
{
removedText = StringTextSource.Empty;
}
else if (length < 100)
{
removedText = new StringTextSource(_rope.ToString(offset, length));
}
else
{
// use a rope if the removed string is long
removedText = new RopeTextSource(_rope.GetRange(offset, length));
}
var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap);
// fire DocumentChanging event
Changing?.Invoke(this, args);
TextChangingInternal?.Invoke(this, args);
_undoStack.Push(this, args);
_cachedText = null; // reset cache of complete document text
_fireTextChanged = true;
var delayedEvents = new DelayedEvents();
lock (_lockObject)
{
// create linked list of checkpoints
_versionProvider.AppendChange(args);
// now update the textBuffer and lineTree
if (offset == 0 && length == _rope.Length)
{
// optimize replacing the whole document
_rope.Clear();
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(0, newRopeTextSource.GetRope());
else
_rope.InsertText(0, newText.Text);
_lineManager.Rebuild();
}
else
{
_rope.RemoveRange(offset, length);
_lineManager.Remove(offset, length);
#if DEBUG
_lineTree.CheckProperties();
#endif
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(offset, newRopeTextSource.GetRope());
else
_rope.InsertText(offset, newText.Text);
_lineManager.Insert(offset, newText);
#if DEBUG
_lineTree.CheckProperties();
#endif
}
}
// update text anchors
if (offsetChangeMap == null)
{
_anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents);
}
else
{
foreach (var entry in offsetChangeMap)
{
_anchorTree.HandleTextChange(entry, delayedEvents);
}
}
_lineManager.ChangeComplete(args);
// raise delayed events after our data structures are consistent again
delayedEvents.RaiseEvents();
// fire DocumentChanged event
Changed?.Invoke(this, args);
TextChangedInternal?.Invoke(this, args);
}
#endregion
#region GetLineBy...
/// <summary>
/// Gets a read-only list of lines.
/// </summary>
/// <remarks><inheritdoc cref="DocumentLine"/></remarks>
public IList<DocumentLine> Lines => _lineTree;
/// <summary>
/// Gets a line by the line number: O(log n)
/// </summary>
public DocumentLine GetLineByNumber(int number)
{
VerifyAccess();
if (number < 1 || number > _lineTree.LineCount)
throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount);
return _lineTree.GetByNumber(number);
}
IDocumentLine IDocument.GetLineByNumber(int lineNumber)
{
return GetLineByNumber(lineNumber);
}
/// <summary>
/// Gets a document lines by offset.
/// Runtime: O(log n)
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")]
public DocumentLine GetLineByOffset(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length);
}
return _lineTree.GetByOffset(offset);
}
IDocumentLine IDocument.GetLineByOffset(int offset)
{
return GetLineByOffset(offset);
}
#endregion
#region GetOffset / GetLocation
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(TextLocation location)
{
return GetOffset(location.Line, location.Column);
}
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(int line, int column)
{
var docLine = GetLineByNumber(line);
if (column <= 0)
return docLine.Offset;
if (column > docLine.Length)
return docLine.EndOffset;
return docLine.Offset + column - 1;
}
/// <summary>
/// Gets the location from an offset.
/// </summary>
/// <seealso cref="GetOffset(TextLocation)"/>
public TextLocation GetLocation(int offset)
{
var line = GetLineByOffset(offset);
return new TextLocation(line.LineNumber, offset - line.Offset + 1);
}
#endregion
#region Line Trackers
private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>();
/// <summary>
/// Gets the list of <see cref="ILineTracker"/>s attached to this document.
/// You can add custom line trackers to this list.
/// </summary>
public IList<ILineTracker> LineTrackers
{
get
{
VerifyAccess();
return _lineTrackers;
}
}
#endregion
#region UndoStack
public UndoStack _undoStack;
/// <summary>
/// Gets the <see cref="UndoStack"/> of the document.
/// </summary>
/// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks>
public UndoStack UndoStack
{
get => _undoStack;
set
{
if (value == null)
throw new ArgumentNullException();
if (value != _undoStack)
{
_undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document
// ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress)
_undoStack = value;
OnPropertyChanged("UndoStack");
}
}
}
#endregion
#region CreateAnchor
/// <summary>
/// Creates a new <see cref="TextAnchor"/> at the specified offset.
/// </summary>
/// <inheritdoc cref="TextAnchor" select="remarks|example"/>
public TextAnchor CreateAnchor(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
return _anchorTree.CreateAnchor(offset);
}
ITextAnchor IDocument.CreateAnchor(int offset)
{
return CreateAnchor(offset);
}
#endregion
#region LineCount
/// <summary>
/// Gets the total number of lines in the document.
/// Runtime: O(1).
/// </summary>
public int LineCount
{
get
{
VerifyAccess();
return _lineTree.LineCount;
}
}
/// <summary>
/// Is raised when the LineCount property changes.
/// </summary>
public event EventHandler LineCountChanged;
#endregion
#region Debugging
[Conditional("DEBUG")]
internal void DebugVerifyAccess()
{
VerifyAccess();
}
/// <summary>
/// Gets the document lines tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetLineTreeAsString()
{
#if DEBUG
return _lineTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
/// <summary>
/// Gets the text anchor tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetTextAnchorTreeAsString()
{
#if DEBUG
return _anchorTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
#endregion
#region Service Provider
private IServiceProvider _serviceProvider;
internal IServiceProvider ServiceProvider
{
get
{
VerifyAccess();
if (_serviceProvider == null)
{
var container = new ServiceContainer();
container.AddService(this);
container.AddService<IDocument>(this);
_serviceProvider = container;
}
return _serviceProvider;
}
set
{
VerifyAccess();
_serviceProvider = value ?? throw new ArgumentNullException(nameof(value));
}
}
object IServiceProvider.GetService(Type serviceType)
{
return ServiceProvider.GetService(serviceType);
}
#endregion
#region FileName
private string _fileName;
/// <inheritdoc/>
public event EventHandler FileNameChanged;
private void OnFileNameChanged(EventArgs e)
{
FileNameChanged?.Invoke(this, e);
}
/// <inheritdoc/>
public string FileName
{
get { return _fileName; }
set
{
if (_fileName != value)
{
_fileName = value;
OnFileNameChanged(EventArgs.Empty);
}
}
}
#endregion
}
}
<MSG> Merge pull request #51 from danwalmsley/fix-thread-verification
verify access checks against thread textdocument is created on.
<DFF> @@ -26,6 +26,7 @@ using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
+using System.Threading;
namespace AvaloniaEdit.Document
{
@@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document
return _rope.ToString(offset, length);
}
+ private Thread ownerThread = Thread.CurrentThread;
+
private void VerifyAccess()
{
- Dispatcher.UIThread.VerifyAccess();
+ if(Thread.CurrentThread != ownerThread)
+ {
+ throw new InvalidOperationException("Call from invalid thread.");
+ }
}
/// <summary>
| 7 | Merge pull request #51 from danwalmsley/fix-thread-verification | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059872 | <NME> TextDocument.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
namespace AvaloniaEdit.Document
{
/// <summary>
/// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events.
/// </summary>
/// <remarks>
/// <b>Thread safety:</b>
/// <inheritdoc cref="VerifyAccess"/>
/// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para>
/// </remarks>
public sealed class TextDocument : IDocument, INotifyPropertyChanged
{
#region Thread ownership
private readonly object _lockObject = new object();
#endregion
#region Fields + Constructor
private readonly Rope<char> _rope;
private readonly DocumentLineTree _lineTree;
private readonly LineManager _lineManager;
private readonly TextAnchorTree _anchorTree;
private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider();
/// <summary>
/// Create an empty text document.
/// </summary>
public TextDocument()
: this(string.Empty.ToCharArray())
{
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(IEnumerable<char> initialText)
{
if (initialText == null)
throw new ArgumentNullException(nameof(initialText));
_rope = new Rope<char>(initialText);
_lineTree = new DocumentLineTree(this);
_lineManager = new LineManager(_lineTree, this);
_lineTrackers.CollectionChanged += delegate
{
_lineManager.UpdateListOfLineTrackers();
};
_anchorTree = new TextAnchorTree(this);
_undoStack = new UndoStack();
FireChangeEvents();
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(ITextSource initialText)
: this(GetTextFromTextSource(initialText))
{
}
// gets the text from a text source, directly retrieving the underlying rope where possible
private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource)
{
if (textSource == null)
throw new ArgumentNullException(nameof(textSource));
if (textSource is RopeTextSource rts)
{
return rts.GetRope();
}
if (textSource is TextDocument doc)
{
return doc._rope;
}
return textSource.Text.ToCharArray();
}
#endregion
#region Text
private void ThrowIfRangeInvalid(int offset, int length)
{
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
if (length < 0 || offset + length > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
}
/// <inheritdoc/>
public string GetText(int offset, int length)
{
VerifyAccess();
return _rope.ToString(offset, length);
}
private void VerifyAccess()
{
Dispatcher.UIThread.VerifyAccess();
}
/// <summary>
public void SetOwnerThread(Thread newOwner)
{
// We need to lock here to ensure that in the null owner case,
// only one thread succeeds in taking ownership.
lock (_lockObject) {
if (ownerThread != null) {
VerifyAccess();
}
ownerThread = newOwner;
}
}
private void VerifyAccess()
{
if(Thread.CurrentThread != ownerThread)
{
throw new InvalidOperationException("Call from invalid thread.");
}
}
/// <summary>
/// Retrieves the text for a portion of the document.
/// </summary>
public string GetText(ISegment segment)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
return GetText(segment.Offset, segment.Length);
}
/// <inheritdoc/>
public int IndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.IndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int LastIndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.LastIndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int IndexOfAny(char[] anyOf, int startIndex, int count)
{
DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds
return _rope.IndexOfAny(anyOf, startIndex, count);
}
/// <inheritdoc/>
public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.IndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.LastIndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public char GetCharAt(int offset)
{
DebugVerifyAccess(); // frequently called, so must be fast in release builds
return _rope[offset];
}
private WeakReference _cachedText;
/// <summary>
/// Gets/Sets the text of the whole document.
/// </summary>
public string Text
{
get
{
VerifyAccess();
var completeText = _cachedText?.Target as string;
if (completeText == null)
{
completeText = _rope.ToString();
_cachedText = new WeakReference(completeText);
}
return completeText;
}
set
{
VerifyAccess();
if (value == null)
throw new ArgumentNullException(nameof(value));
Replace(0, _rope.Length, value);
}
}
/// <summary>
/// This event is called after a group of changes is completed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextChanged;
event EventHandler IDocument.ChangeCompleted
{
add => TextChanged += value;
remove => TextChanged -= value;
}
/// <inheritdoc/>
public int TextLength
{
get
{
VerifyAccess();
return _rope.Length;
}
}
/// <summary>
/// Is raised when the TextLength property changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextLengthChanged;
/// <summary>
/// Is raised before the document changes.
/// </summary>
/// <remarks>
/// <para>Here is the order in which events are raised during a document update:</para>
/// <list type="bullet">
/// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description>Start of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateStarted"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="Changing"/> event is raised</description></item>
/// <item><description>The document is changed</description></item>
/// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were
/// in the deleted text portion</description></item>
/// <item><description><see cref="Changed"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="TextChanged"/> event is raised</description></item>
/// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item>
/// <item><description>End of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateFinished"/> event is raised</description></item>
/// </list></item>
/// </list>
/// <para>
/// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>,
/// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>.
/// </para><para>
/// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls.
/// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done.
/// </para><para>
/// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step.
/// </para>
/// </remarks>
public event EventHandler<DocumentChangeEventArgs> Changing;
// Unfortunately EventHandler<T> is invariant, so we have to use two separate events
private event EventHandler<TextChangeEventArgs> TextChangingInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanging
{
add => TextChangingInternal += value;
remove => TextChangingInternal -= value;
}
/// <summary>
/// Is raised after the document has changed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler<DocumentChangeEventArgs> Changed;
private event EventHandler<TextChangeEventArgs> TextChangedInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanged
{
add => TextChangedInternal += value;
remove => TextChangedInternal -= value;
}
/// <summary>
/// Creates a snapshot of the current text.
/// </summary>
/// <remarks>
/// <para>This method returns an immutable snapshot of the document, and may be safely called even when
/// the document's owner thread is concurrently modifying the document.
/// </para><para>
/// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other
/// classes implementing ITextSource.CreateSnapshot().
/// </para><para>
/// </para>
/// </remarks>
public ITextSource CreateSnapshot()
{
lock (_lockObject)
{
return new RopeTextSource(_rope, _versionProvider.CurrentVersion);
}
}
/// <summary>
/// Creates a snapshot of a part of the current text.
/// </summary>
/// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks>
public ITextSource CreateSnapshot(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextSource(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public ITextSourceVersion Version => _versionProvider.CurrentVersion;
/// <inheritdoc/>
public TextReader CreateReader()
{
lock (_lockObject)
{
return new RopeTextReader(_rope);
}
}
/// <inheritdoc/>
public TextReader CreateReader(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextReader(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer)
{
VerifyAccess();
_rope.WriteTo(writer, 0, _rope.Length);
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer, int offset, int length)
{
VerifyAccess();
_rope.WriteTo(writer, offset, length);
}
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region BeginUpdate / EndUpdate
private int _beginUpdateCount;
/// <summary>
/// Gets if an update is running.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public bool IsInUpdate
{
get
{
VerifyAccess();
return _beginUpdateCount > 0;
}
}
/// <summary>
/// Immediately calls <see cref="BeginUpdate()"/>,
/// and returns an IDisposable that calls <see cref="EndUpdate()"/>.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public IDisposable RunUpdate()
{
BeginUpdate();
return new CallbackOnDispose(EndUpdate);
}
/// <summary>
/// <para>Begins a group of document changes.</para>
/// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will
/// group all changes into a single action.</para>
/// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number
/// of EndUpdate calls the events resume their work.</para>
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void BeginUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot change document within another document change.");
_beginUpdateCount++;
if (_beginUpdateCount == 1)
{
_undoStack.StartUndoGroup();
UpdateStarted?.Invoke(this, EventArgs.Empty);
}
}
/// <summary>
/// Ends a group of document changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void EndUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot end update within document change.");
if (_beginUpdateCount == 0)
throw new InvalidOperationException("No update is active.");
if (_beginUpdateCount == 1)
{
// fire change events inside the change group - event handlers might add additional
// document changes to the change group
FireChangeEvents();
_undoStack.EndUndoGroup();
_beginUpdateCount = 0;
UpdateFinished?.Invoke(this, EventArgs.Empty);
}
else
{
_beginUpdateCount -= 1;
}
}
/// <summary>
/// Occurs when a document change starts.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateStarted;
/// <summary>
/// Occurs when a document change is finished.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateFinished;
void IDocument.StartUndoableAction()
{
BeginUpdate();
}
void IDocument.EndUndoableAction()
{
EndUpdate();
}
IDisposable IDocument.OpenUndoGroup()
{
return RunUpdate();
}
#endregion
#region Fire events after update
private int _oldTextLength;
private int _oldLineCount;
private bool _fireTextChanged;
/// <summary>
/// Fires TextChanged, TextLengthChanged, LineCountChanged if required.
/// </summary>
internal void FireChangeEvents()
{
// it may be necessary to fire the event multiple times if the document is changed
// from inside the event handlers
while (_fireTextChanged)
{
_fireTextChanged = false;
TextChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("Text");
var textLength = _rope.Length;
if (textLength != _oldTextLength)
{
_oldTextLength = textLength;
TextLengthChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("TextLength");
}
var lineCount = _lineTree.LineCount;
if (lineCount != _oldLineCount)
{
_oldLineCount = lineCount;
LineCountChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("LineCount");
}
}
}
#endregion
#region Insert / Remove / Replace
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, string text)
{
Replace(offset, 0, new StringTextSource(text), null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, ITextSource text)
{
Replace(offset, 0, text, null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, new StringTextSource(text), null);
}
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, text, null);
}
}
/// <summary>
/// Removes text.
/// </summary>
public void Remove(ISegment segment)
{
Replace(segment, string.Empty);
}
/// <summary>
/// Removes text.
/// </summary>
/// <param name="offset">Starting offset of the text to be removed.</param>
/// <param name="length">Length of the text to be removed.</param>
public void Remove(int offset, int length)
{
Replace(offset, length, StringTextSource.Empty);
}
internal bool InDocumentChanging;
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, string text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, ITextSource text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, string text)
{
Replace(offset, length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, ITextSource text)
{
Replace(offset, length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMappingType);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType)
{
if (text == null)
throw new ArgumentNullException(nameof(text));
// Please see OffsetChangeMappingType XML comments for details on how these modes work.
switch (offsetChangeMappingType)
{
case OffsetChangeMappingType.Normal:
Replace(offset, length, text, null);
break;
case OffsetChangeMappingType.KeepAnchorBeforeInsertion:
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(
new OffsetChangeMapEntry(offset, length, text.TextLength, false, true)));
break;
case OffsetChangeMappingType.RemoveAndInsert:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else
{
var map = new OffsetChangeMap(2)
{
new OffsetChangeMapEntry(offset, length, 0),
new OffsetChangeMapEntry(offset, 0, text.TextLength)
};
map.Freeze();
Replace(offset, length, text, map);
}
break;
case OffsetChangeMappingType.CharacterReplace:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else if (text.TextLength > length)
{
// look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace
// the last character
var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else if (text.TextLength < length)
{
var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else
{
Replace(offset, length, text, OffsetChangeMap.Empty);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value");
}
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMap);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap)
{
text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text));
offsetChangeMap?.Freeze();
// Ensure that all changes take place inside an update group.
// Will also take care of throwing an exception if inDocumentChanging is set.
BeginUpdate();
try
{
// protect document change against corruption by other changes inside the event handlers
InDocumentChanging = true;
try
{
// The range verification must wait until after the BeginUpdate() call because the document
// might be modified inside the UpdateStarted event.
ThrowIfRangeInvalid(offset, length);
DoReplace(offset, length, text, offsetChangeMap);
}
finally
{
InDocumentChanging = false;
}
}
finally
{
EndUpdate();
}
}
private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap)
{
if (length == 0 && newText.TextLength == 0)
return;
// trying to replace a single character in 'Normal' mode?
// for single characters, 'CharacterReplace' mode is equivalent, but more performant
// (we don't have to touch the anchorTree at all in 'CharacterReplace' mode)
if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null)
offsetChangeMap = OffsetChangeMap.Empty;
ITextSource removedText;
if (length == 0)
{
removedText = StringTextSource.Empty;
}
else if (length < 100)
{
removedText = new StringTextSource(_rope.ToString(offset, length));
}
else
{
// use a rope if the removed string is long
removedText = new RopeTextSource(_rope.GetRange(offset, length));
}
var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap);
// fire DocumentChanging event
Changing?.Invoke(this, args);
TextChangingInternal?.Invoke(this, args);
_undoStack.Push(this, args);
_cachedText = null; // reset cache of complete document text
_fireTextChanged = true;
var delayedEvents = new DelayedEvents();
lock (_lockObject)
{
// create linked list of checkpoints
_versionProvider.AppendChange(args);
// now update the textBuffer and lineTree
if (offset == 0 && length == _rope.Length)
{
// optimize replacing the whole document
_rope.Clear();
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(0, newRopeTextSource.GetRope());
else
_rope.InsertText(0, newText.Text);
_lineManager.Rebuild();
}
else
{
_rope.RemoveRange(offset, length);
_lineManager.Remove(offset, length);
#if DEBUG
_lineTree.CheckProperties();
#endif
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(offset, newRopeTextSource.GetRope());
else
_rope.InsertText(offset, newText.Text);
_lineManager.Insert(offset, newText);
#if DEBUG
_lineTree.CheckProperties();
#endif
}
}
// update text anchors
if (offsetChangeMap == null)
{
_anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents);
}
else
{
foreach (var entry in offsetChangeMap)
{
_anchorTree.HandleTextChange(entry, delayedEvents);
}
}
_lineManager.ChangeComplete(args);
// raise delayed events after our data structures are consistent again
delayedEvents.RaiseEvents();
// fire DocumentChanged event
Changed?.Invoke(this, args);
TextChangedInternal?.Invoke(this, args);
}
#endregion
#region GetLineBy...
/// <summary>
/// Gets a read-only list of lines.
/// </summary>
/// <remarks><inheritdoc cref="DocumentLine"/></remarks>
public IList<DocumentLine> Lines => _lineTree;
/// <summary>
/// Gets a line by the line number: O(log n)
/// </summary>
public DocumentLine GetLineByNumber(int number)
{
VerifyAccess();
if (number < 1 || number > _lineTree.LineCount)
throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount);
return _lineTree.GetByNumber(number);
}
IDocumentLine IDocument.GetLineByNumber(int lineNumber)
{
return GetLineByNumber(lineNumber);
}
/// <summary>
/// Gets a document lines by offset.
/// Runtime: O(log n)
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")]
public DocumentLine GetLineByOffset(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length);
}
return _lineTree.GetByOffset(offset);
}
IDocumentLine IDocument.GetLineByOffset(int offset)
{
return GetLineByOffset(offset);
}
#endregion
#region GetOffset / GetLocation
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(TextLocation location)
{
return GetOffset(location.Line, location.Column);
}
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(int line, int column)
{
var docLine = GetLineByNumber(line);
if (column <= 0)
return docLine.Offset;
if (column > docLine.Length)
return docLine.EndOffset;
return docLine.Offset + column - 1;
}
/// <summary>
/// Gets the location from an offset.
/// </summary>
/// <seealso cref="GetOffset(TextLocation)"/>
public TextLocation GetLocation(int offset)
{
var line = GetLineByOffset(offset);
return new TextLocation(line.LineNumber, offset - line.Offset + 1);
}
#endregion
#region Line Trackers
private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>();
/// <summary>
/// Gets the list of <see cref="ILineTracker"/>s attached to this document.
/// You can add custom line trackers to this list.
/// </summary>
public IList<ILineTracker> LineTrackers
{
get
{
VerifyAccess();
return _lineTrackers;
}
}
#endregion
#region UndoStack
public UndoStack _undoStack;
/// <summary>
/// Gets the <see cref="UndoStack"/> of the document.
/// </summary>
/// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks>
public UndoStack UndoStack
{
get => _undoStack;
set
{
if (value == null)
throw new ArgumentNullException();
if (value != _undoStack)
{
_undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document
// ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress)
_undoStack = value;
OnPropertyChanged("UndoStack");
}
}
}
#endregion
#region CreateAnchor
/// <summary>
/// Creates a new <see cref="TextAnchor"/> at the specified offset.
/// </summary>
/// <inheritdoc cref="TextAnchor" select="remarks|example"/>
public TextAnchor CreateAnchor(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
return _anchorTree.CreateAnchor(offset);
}
ITextAnchor IDocument.CreateAnchor(int offset)
{
return CreateAnchor(offset);
}
#endregion
#region LineCount
/// <summary>
/// Gets the total number of lines in the document.
/// Runtime: O(1).
/// </summary>
public int LineCount
{
get
{
VerifyAccess();
return _lineTree.LineCount;
}
}
/// <summary>
/// Is raised when the LineCount property changes.
/// </summary>
public event EventHandler LineCountChanged;
#endregion
#region Debugging
[Conditional("DEBUG")]
internal void DebugVerifyAccess()
{
VerifyAccess();
}
/// <summary>
/// Gets the document lines tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetLineTreeAsString()
{
#if DEBUG
return _lineTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
/// <summary>
/// Gets the text anchor tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetTextAnchorTreeAsString()
{
#if DEBUG
return _anchorTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
#endregion
#region Service Provider
private IServiceProvider _serviceProvider;
internal IServiceProvider ServiceProvider
{
get
{
VerifyAccess();
if (_serviceProvider == null)
{
var container = new ServiceContainer();
container.AddService(this);
container.AddService<IDocument>(this);
_serviceProvider = container;
}
return _serviceProvider;
}
set
{
VerifyAccess();
_serviceProvider = value ?? throw new ArgumentNullException(nameof(value));
}
}
object IServiceProvider.GetService(Type serviceType)
{
return ServiceProvider.GetService(serviceType);
}
#endregion
#region FileName
private string _fileName;
/// <inheritdoc/>
public event EventHandler FileNameChanged;
private void OnFileNameChanged(EventArgs e)
{
FileNameChanged?.Invoke(this, e);
}
/// <inheritdoc/>
public string FileName
{
get { return _fileName; }
set
{
if (_fileName != value)
{
_fileName = value;
OnFileNameChanged(EventArgs.Empty);
}
}
}
#endregion
}
}
<MSG> Merge pull request #51 from danwalmsley/fix-thread-verification
verify access checks against thread textdocument is created on.
<DFF> @@ -26,6 +26,7 @@ using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
+using System.Threading;
namespace AvaloniaEdit.Document
{
@@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document
return _rope.ToString(offset, length);
}
+ private Thread ownerThread = Thread.CurrentThread;
+
private void VerifyAccess()
{
- Dispatcher.UIThread.VerifyAccess();
+ if(Thread.CurrentThread != ownerThread)
+ {
+ throw new InvalidOperationException("Call from invalid thread.");
+ }
}
/// <summary>
| 7 | Merge pull request #51 from danwalmsley/fix-thread-verification | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059873 | <NME> TextDocument.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
namespace AvaloniaEdit.Document
{
/// <summary>
/// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events.
/// </summary>
/// <remarks>
/// <b>Thread safety:</b>
/// <inheritdoc cref="VerifyAccess"/>
/// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para>
/// </remarks>
public sealed class TextDocument : IDocument, INotifyPropertyChanged
{
#region Thread ownership
private readonly object _lockObject = new object();
#endregion
#region Fields + Constructor
private readonly Rope<char> _rope;
private readonly DocumentLineTree _lineTree;
private readonly LineManager _lineManager;
private readonly TextAnchorTree _anchorTree;
private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider();
/// <summary>
/// Create an empty text document.
/// </summary>
public TextDocument()
: this(string.Empty.ToCharArray())
{
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(IEnumerable<char> initialText)
{
if (initialText == null)
throw new ArgumentNullException(nameof(initialText));
_rope = new Rope<char>(initialText);
_lineTree = new DocumentLineTree(this);
_lineManager = new LineManager(_lineTree, this);
_lineTrackers.CollectionChanged += delegate
{
_lineManager.UpdateListOfLineTrackers();
};
_anchorTree = new TextAnchorTree(this);
_undoStack = new UndoStack();
FireChangeEvents();
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(ITextSource initialText)
: this(GetTextFromTextSource(initialText))
{
}
// gets the text from a text source, directly retrieving the underlying rope where possible
private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource)
{
if (textSource == null)
throw new ArgumentNullException(nameof(textSource));
if (textSource is RopeTextSource rts)
{
return rts.GetRope();
}
if (textSource is TextDocument doc)
{
return doc._rope;
}
return textSource.Text.ToCharArray();
}
#endregion
#region Text
private void ThrowIfRangeInvalid(int offset, int length)
{
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
if (length < 0 || offset + length > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
}
/// <inheritdoc/>
public string GetText(int offset, int length)
{
VerifyAccess();
return _rope.ToString(offset, length);
}
private void VerifyAccess()
{
Dispatcher.UIThread.VerifyAccess();
}
/// <summary>
public void SetOwnerThread(Thread newOwner)
{
// We need to lock here to ensure that in the null owner case,
// only one thread succeeds in taking ownership.
lock (_lockObject) {
if (ownerThread != null) {
VerifyAccess();
}
ownerThread = newOwner;
}
}
private void VerifyAccess()
{
if(Thread.CurrentThread != ownerThread)
{
throw new InvalidOperationException("Call from invalid thread.");
}
}
/// <summary>
/// Retrieves the text for a portion of the document.
/// </summary>
public string GetText(ISegment segment)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
return GetText(segment.Offset, segment.Length);
}
/// <inheritdoc/>
public int IndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.IndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int LastIndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.LastIndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int IndexOfAny(char[] anyOf, int startIndex, int count)
{
DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds
return _rope.IndexOfAny(anyOf, startIndex, count);
}
/// <inheritdoc/>
public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.IndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.LastIndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public char GetCharAt(int offset)
{
DebugVerifyAccess(); // frequently called, so must be fast in release builds
return _rope[offset];
}
private WeakReference _cachedText;
/// <summary>
/// Gets/Sets the text of the whole document.
/// </summary>
public string Text
{
get
{
VerifyAccess();
var completeText = _cachedText?.Target as string;
if (completeText == null)
{
completeText = _rope.ToString();
_cachedText = new WeakReference(completeText);
}
return completeText;
}
set
{
VerifyAccess();
if (value == null)
throw new ArgumentNullException(nameof(value));
Replace(0, _rope.Length, value);
}
}
/// <summary>
/// This event is called after a group of changes is completed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextChanged;
event EventHandler IDocument.ChangeCompleted
{
add => TextChanged += value;
remove => TextChanged -= value;
}
/// <inheritdoc/>
public int TextLength
{
get
{
VerifyAccess();
return _rope.Length;
}
}
/// <summary>
/// Is raised when the TextLength property changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextLengthChanged;
/// <summary>
/// Is raised before the document changes.
/// </summary>
/// <remarks>
/// <para>Here is the order in which events are raised during a document update:</para>
/// <list type="bullet">
/// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description>Start of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateStarted"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="Changing"/> event is raised</description></item>
/// <item><description>The document is changed</description></item>
/// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were
/// in the deleted text portion</description></item>
/// <item><description><see cref="Changed"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="TextChanged"/> event is raised</description></item>
/// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item>
/// <item><description>End of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateFinished"/> event is raised</description></item>
/// </list></item>
/// </list>
/// <para>
/// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>,
/// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>.
/// </para><para>
/// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls.
/// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done.
/// </para><para>
/// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step.
/// </para>
/// </remarks>
public event EventHandler<DocumentChangeEventArgs> Changing;
// Unfortunately EventHandler<T> is invariant, so we have to use two separate events
private event EventHandler<TextChangeEventArgs> TextChangingInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanging
{
add => TextChangingInternal += value;
remove => TextChangingInternal -= value;
}
/// <summary>
/// Is raised after the document has changed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler<DocumentChangeEventArgs> Changed;
private event EventHandler<TextChangeEventArgs> TextChangedInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanged
{
add => TextChangedInternal += value;
remove => TextChangedInternal -= value;
}
/// <summary>
/// Creates a snapshot of the current text.
/// </summary>
/// <remarks>
/// <para>This method returns an immutable snapshot of the document, and may be safely called even when
/// the document's owner thread is concurrently modifying the document.
/// </para><para>
/// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other
/// classes implementing ITextSource.CreateSnapshot().
/// </para><para>
/// </para>
/// </remarks>
public ITextSource CreateSnapshot()
{
lock (_lockObject)
{
return new RopeTextSource(_rope, _versionProvider.CurrentVersion);
}
}
/// <summary>
/// Creates a snapshot of a part of the current text.
/// </summary>
/// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks>
public ITextSource CreateSnapshot(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextSource(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public ITextSourceVersion Version => _versionProvider.CurrentVersion;
/// <inheritdoc/>
public TextReader CreateReader()
{
lock (_lockObject)
{
return new RopeTextReader(_rope);
}
}
/// <inheritdoc/>
public TextReader CreateReader(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextReader(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer)
{
VerifyAccess();
_rope.WriteTo(writer, 0, _rope.Length);
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer, int offset, int length)
{
VerifyAccess();
_rope.WriteTo(writer, offset, length);
}
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region BeginUpdate / EndUpdate
private int _beginUpdateCount;
/// <summary>
/// Gets if an update is running.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public bool IsInUpdate
{
get
{
VerifyAccess();
return _beginUpdateCount > 0;
}
}
/// <summary>
/// Immediately calls <see cref="BeginUpdate()"/>,
/// and returns an IDisposable that calls <see cref="EndUpdate()"/>.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public IDisposable RunUpdate()
{
BeginUpdate();
return new CallbackOnDispose(EndUpdate);
}
/// <summary>
/// <para>Begins a group of document changes.</para>
/// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will
/// group all changes into a single action.</para>
/// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number
/// of EndUpdate calls the events resume their work.</para>
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void BeginUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot change document within another document change.");
_beginUpdateCount++;
if (_beginUpdateCount == 1)
{
_undoStack.StartUndoGroup();
UpdateStarted?.Invoke(this, EventArgs.Empty);
}
}
/// <summary>
/// Ends a group of document changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void EndUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot end update within document change.");
if (_beginUpdateCount == 0)
throw new InvalidOperationException("No update is active.");
if (_beginUpdateCount == 1)
{
// fire change events inside the change group - event handlers might add additional
// document changes to the change group
FireChangeEvents();
_undoStack.EndUndoGroup();
_beginUpdateCount = 0;
UpdateFinished?.Invoke(this, EventArgs.Empty);
}
else
{
_beginUpdateCount -= 1;
}
}
/// <summary>
/// Occurs when a document change starts.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateStarted;
/// <summary>
/// Occurs when a document change is finished.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateFinished;
void IDocument.StartUndoableAction()
{
BeginUpdate();
}
void IDocument.EndUndoableAction()
{
EndUpdate();
}
IDisposable IDocument.OpenUndoGroup()
{
return RunUpdate();
}
#endregion
#region Fire events after update
private int _oldTextLength;
private int _oldLineCount;
private bool _fireTextChanged;
/// <summary>
/// Fires TextChanged, TextLengthChanged, LineCountChanged if required.
/// </summary>
internal void FireChangeEvents()
{
// it may be necessary to fire the event multiple times if the document is changed
// from inside the event handlers
while (_fireTextChanged)
{
_fireTextChanged = false;
TextChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("Text");
var textLength = _rope.Length;
if (textLength != _oldTextLength)
{
_oldTextLength = textLength;
TextLengthChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("TextLength");
}
var lineCount = _lineTree.LineCount;
if (lineCount != _oldLineCount)
{
_oldLineCount = lineCount;
LineCountChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("LineCount");
}
}
}
#endregion
#region Insert / Remove / Replace
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, string text)
{
Replace(offset, 0, new StringTextSource(text), null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, ITextSource text)
{
Replace(offset, 0, text, null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, new StringTextSource(text), null);
}
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, text, null);
}
}
/// <summary>
/// Removes text.
/// </summary>
public void Remove(ISegment segment)
{
Replace(segment, string.Empty);
}
/// <summary>
/// Removes text.
/// </summary>
/// <param name="offset">Starting offset of the text to be removed.</param>
/// <param name="length">Length of the text to be removed.</param>
public void Remove(int offset, int length)
{
Replace(offset, length, StringTextSource.Empty);
}
internal bool InDocumentChanging;
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, string text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, ITextSource text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, string text)
{
Replace(offset, length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, ITextSource text)
{
Replace(offset, length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMappingType);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType)
{
if (text == null)
throw new ArgumentNullException(nameof(text));
// Please see OffsetChangeMappingType XML comments for details on how these modes work.
switch (offsetChangeMappingType)
{
case OffsetChangeMappingType.Normal:
Replace(offset, length, text, null);
break;
case OffsetChangeMappingType.KeepAnchorBeforeInsertion:
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(
new OffsetChangeMapEntry(offset, length, text.TextLength, false, true)));
break;
case OffsetChangeMappingType.RemoveAndInsert:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else
{
var map = new OffsetChangeMap(2)
{
new OffsetChangeMapEntry(offset, length, 0),
new OffsetChangeMapEntry(offset, 0, text.TextLength)
};
map.Freeze();
Replace(offset, length, text, map);
}
break;
case OffsetChangeMappingType.CharacterReplace:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else if (text.TextLength > length)
{
// look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace
// the last character
var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else if (text.TextLength < length)
{
var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else
{
Replace(offset, length, text, OffsetChangeMap.Empty);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value");
}
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMap);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap)
{
text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text));
offsetChangeMap?.Freeze();
// Ensure that all changes take place inside an update group.
// Will also take care of throwing an exception if inDocumentChanging is set.
BeginUpdate();
try
{
// protect document change against corruption by other changes inside the event handlers
InDocumentChanging = true;
try
{
// The range verification must wait until after the BeginUpdate() call because the document
// might be modified inside the UpdateStarted event.
ThrowIfRangeInvalid(offset, length);
DoReplace(offset, length, text, offsetChangeMap);
}
finally
{
InDocumentChanging = false;
}
}
finally
{
EndUpdate();
}
}
private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap)
{
if (length == 0 && newText.TextLength == 0)
return;
// trying to replace a single character in 'Normal' mode?
// for single characters, 'CharacterReplace' mode is equivalent, but more performant
// (we don't have to touch the anchorTree at all in 'CharacterReplace' mode)
if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null)
offsetChangeMap = OffsetChangeMap.Empty;
ITextSource removedText;
if (length == 0)
{
removedText = StringTextSource.Empty;
}
else if (length < 100)
{
removedText = new StringTextSource(_rope.ToString(offset, length));
}
else
{
// use a rope if the removed string is long
removedText = new RopeTextSource(_rope.GetRange(offset, length));
}
var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap);
// fire DocumentChanging event
Changing?.Invoke(this, args);
TextChangingInternal?.Invoke(this, args);
_undoStack.Push(this, args);
_cachedText = null; // reset cache of complete document text
_fireTextChanged = true;
var delayedEvents = new DelayedEvents();
lock (_lockObject)
{
// create linked list of checkpoints
_versionProvider.AppendChange(args);
// now update the textBuffer and lineTree
if (offset == 0 && length == _rope.Length)
{
// optimize replacing the whole document
_rope.Clear();
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(0, newRopeTextSource.GetRope());
else
_rope.InsertText(0, newText.Text);
_lineManager.Rebuild();
}
else
{
_rope.RemoveRange(offset, length);
_lineManager.Remove(offset, length);
#if DEBUG
_lineTree.CheckProperties();
#endif
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(offset, newRopeTextSource.GetRope());
else
_rope.InsertText(offset, newText.Text);
_lineManager.Insert(offset, newText);
#if DEBUG
_lineTree.CheckProperties();
#endif
}
}
// update text anchors
if (offsetChangeMap == null)
{
_anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents);
}
else
{
foreach (var entry in offsetChangeMap)
{
_anchorTree.HandleTextChange(entry, delayedEvents);
}
}
_lineManager.ChangeComplete(args);
// raise delayed events after our data structures are consistent again
delayedEvents.RaiseEvents();
// fire DocumentChanged event
Changed?.Invoke(this, args);
TextChangedInternal?.Invoke(this, args);
}
#endregion
#region GetLineBy...
/// <summary>
/// Gets a read-only list of lines.
/// </summary>
/// <remarks><inheritdoc cref="DocumentLine"/></remarks>
public IList<DocumentLine> Lines => _lineTree;
/// <summary>
/// Gets a line by the line number: O(log n)
/// </summary>
public DocumentLine GetLineByNumber(int number)
{
VerifyAccess();
if (number < 1 || number > _lineTree.LineCount)
throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount);
return _lineTree.GetByNumber(number);
}
IDocumentLine IDocument.GetLineByNumber(int lineNumber)
{
return GetLineByNumber(lineNumber);
}
/// <summary>
/// Gets a document lines by offset.
/// Runtime: O(log n)
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")]
public DocumentLine GetLineByOffset(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length);
}
return _lineTree.GetByOffset(offset);
}
IDocumentLine IDocument.GetLineByOffset(int offset)
{
return GetLineByOffset(offset);
}
#endregion
#region GetOffset / GetLocation
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(TextLocation location)
{
return GetOffset(location.Line, location.Column);
}
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(int line, int column)
{
var docLine = GetLineByNumber(line);
if (column <= 0)
return docLine.Offset;
if (column > docLine.Length)
return docLine.EndOffset;
return docLine.Offset + column - 1;
}
/// <summary>
/// Gets the location from an offset.
/// </summary>
/// <seealso cref="GetOffset(TextLocation)"/>
public TextLocation GetLocation(int offset)
{
var line = GetLineByOffset(offset);
return new TextLocation(line.LineNumber, offset - line.Offset + 1);
}
#endregion
#region Line Trackers
private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>();
/// <summary>
/// Gets the list of <see cref="ILineTracker"/>s attached to this document.
/// You can add custom line trackers to this list.
/// </summary>
public IList<ILineTracker> LineTrackers
{
get
{
VerifyAccess();
return _lineTrackers;
}
}
#endregion
#region UndoStack
public UndoStack _undoStack;
/// <summary>
/// Gets the <see cref="UndoStack"/> of the document.
/// </summary>
/// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks>
public UndoStack UndoStack
{
get => _undoStack;
set
{
if (value == null)
throw new ArgumentNullException();
if (value != _undoStack)
{
_undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document
// ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress)
_undoStack = value;
OnPropertyChanged("UndoStack");
}
}
}
#endregion
#region CreateAnchor
/// <summary>
/// Creates a new <see cref="TextAnchor"/> at the specified offset.
/// </summary>
/// <inheritdoc cref="TextAnchor" select="remarks|example"/>
public TextAnchor CreateAnchor(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
return _anchorTree.CreateAnchor(offset);
}
ITextAnchor IDocument.CreateAnchor(int offset)
{
return CreateAnchor(offset);
}
#endregion
#region LineCount
/// <summary>
/// Gets the total number of lines in the document.
/// Runtime: O(1).
/// </summary>
public int LineCount
{
get
{
VerifyAccess();
return _lineTree.LineCount;
}
}
/// <summary>
/// Is raised when the LineCount property changes.
/// </summary>
public event EventHandler LineCountChanged;
#endregion
#region Debugging
[Conditional("DEBUG")]
internal void DebugVerifyAccess()
{
VerifyAccess();
}
/// <summary>
/// Gets the document lines tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetLineTreeAsString()
{
#if DEBUG
return _lineTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
/// <summary>
/// Gets the text anchor tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetTextAnchorTreeAsString()
{
#if DEBUG
return _anchorTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
#endregion
#region Service Provider
private IServiceProvider _serviceProvider;
internal IServiceProvider ServiceProvider
{
get
{
VerifyAccess();
if (_serviceProvider == null)
{
var container = new ServiceContainer();
container.AddService(this);
container.AddService<IDocument>(this);
_serviceProvider = container;
}
return _serviceProvider;
}
set
{
VerifyAccess();
_serviceProvider = value ?? throw new ArgumentNullException(nameof(value));
}
}
object IServiceProvider.GetService(Type serviceType)
{
return ServiceProvider.GetService(serviceType);
}
#endregion
#region FileName
private string _fileName;
/// <inheritdoc/>
public event EventHandler FileNameChanged;
private void OnFileNameChanged(EventArgs e)
{
FileNameChanged?.Invoke(this, e);
}
/// <inheritdoc/>
public string FileName
{
get { return _fileName; }
set
{
if (_fileName != value)
{
_fileName = value;
OnFileNameChanged(EventArgs.Empty);
}
}
}
#endregion
}
}
<MSG> Merge pull request #51 from danwalmsley/fix-thread-verification
verify access checks against thread textdocument is created on.
<DFF> @@ -26,6 +26,7 @@ using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
+using System.Threading;
namespace AvaloniaEdit.Document
{
@@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document
return _rope.ToString(offset, length);
}
+ private Thread ownerThread = Thread.CurrentThread;
+
private void VerifyAccess()
{
- Dispatcher.UIThread.VerifyAccess();
+ if(Thread.CurrentThread != ownerThread)
+ {
+ throw new InvalidOperationException("Call from invalid thread.");
+ }
}
/// <summary>
| 7 | Merge pull request #51 from danwalmsley/fix-thread-verification | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059874 | <NME> TextDocument.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
namespace AvaloniaEdit.Document
{
/// <summary>
/// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events.
/// </summary>
/// <remarks>
/// <b>Thread safety:</b>
/// <inheritdoc cref="VerifyAccess"/>
/// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para>
/// </remarks>
public sealed class TextDocument : IDocument, INotifyPropertyChanged
{
#region Thread ownership
private readonly object _lockObject = new object();
#endregion
#region Fields + Constructor
private readonly Rope<char> _rope;
private readonly DocumentLineTree _lineTree;
private readonly LineManager _lineManager;
private readonly TextAnchorTree _anchorTree;
private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider();
/// <summary>
/// Create an empty text document.
/// </summary>
public TextDocument()
: this(string.Empty.ToCharArray())
{
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(IEnumerable<char> initialText)
{
if (initialText == null)
throw new ArgumentNullException(nameof(initialText));
_rope = new Rope<char>(initialText);
_lineTree = new DocumentLineTree(this);
_lineManager = new LineManager(_lineTree, this);
_lineTrackers.CollectionChanged += delegate
{
_lineManager.UpdateListOfLineTrackers();
};
_anchorTree = new TextAnchorTree(this);
_undoStack = new UndoStack();
FireChangeEvents();
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(ITextSource initialText)
: this(GetTextFromTextSource(initialText))
{
}
// gets the text from a text source, directly retrieving the underlying rope where possible
private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource)
{
if (textSource == null)
throw new ArgumentNullException(nameof(textSource));
if (textSource is RopeTextSource rts)
{
return rts.GetRope();
}
if (textSource is TextDocument doc)
{
return doc._rope;
}
return textSource.Text.ToCharArray();
}
#endregion
#region Text
private void ThrowIfRangeInvalid(int offset, int length)
{
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
if (length < 0 || offset + length > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
}
/// <inheritdoc/>
public string GetText(int offset, int length)
{
VerifyAccess();
return _rope.ToString(offset, length);
}
private void VerifyAccess()
{
Dispatcher.UIThread.VerifyAccess();
}
/// <summary>
public void SetOwnerThread(Thread newOwner)
{
// We need to lock here to ensure that in the null owner case,
// only one thread succeeds in taking ownership.
lock (_lockObject) {
if (ownerThread != null) {
VerifyAccess();
}
ownerThread = newOwner;
}
}
private void VerifyAccess()
{
if(Thread.CurrentThread != ownerThread)
{
throw new InvalidOperationException("Call from invalid thread.");
}
}
/// <summary>
/// Retrieves the text for a portion of the document.
/// </summary>
public string GetText(ISegment segment)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
return GetText(segment.Offset, segment.Length);
}
/// <inheritdoc/>
public int IndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.IndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int LastIndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.LastIndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int IndexOfAny(char[] anyOf, int startIndex, int count)
{
DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds
return _rope.IndexOfAny(anyOf, startIndex, count);
}
/// <inheritdoc/>
public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.IndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.LastIndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public char GetCharAt(int offset)
{
DebugVerifyAccess(); // frequently called, so must be fast in release builds
return _rope[offset];
}
private WeakReference _cachedText;
/// <summary>
/// Gets/Sets the text of the whole document.
/// </summary>
public string Text
{
get
{
VerifyAccess();
var completeText = _cachedText?.Target as string;
if (completeText == null)
{
completeText = _rope.ToString();
_cachedText = new WeakReference(completeText);
}
return completeText;
}
set
{
VerifyAccess();
if (value == null)
throw new ArgumentNullException(nameof(value));
Replace(0, _rope.Length, value);
}
}
/// <summary>
/// This event is called after a group of changes is completed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextChanged;
event EventHandler IDocument.ChangeCompleted
{
add => TextChanged += value;
remove => TextChanged -= value;
}
/// <inheritdoc/>
public int TextLength
{
get
{
VerifyAccess();
return _rope.Length;
}
}
/// <summary>
/// Is raised when the TextLength property changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextLengthChanged;
/// <summary>
/// Is raised before the document changes.
/// </summary>
/// <remarks>
/// <para>Here is the order in which events are raised during a document update:</para>
/// <list type="bullet">
/// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description>Start of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateStarted"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="Changing"/> event is raised</description></item>
/// <item><description>The document is changed</description></item>
/// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were
/// in the deleted text portion</description></item>
/// <item><description><see cref="Changed"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="TextChanged"/> event is raised</description></item>
/// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item>
/// <item><description>End of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateFinished"/> event is raised</description></item>
/// </list></item>
/// </list>
/// <para>
/// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>,
/// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>.
/// </para><para>
/// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls.
/// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done.
/// </para><para>
/// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step.
/// </para>
/// </remarks>
public event EventHandler<DocumentChangeEventArgs> Changing;
// Unfortunately EventHandler<T> is invariant, so we have to use two separate events
private event EventHandler<TextChangeEventArgs> TextChangingInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanging
{
add => TextChangingInternal += value;
remove => TextChangingInternal -= value;
}
/// <summary>
/// Is raised after the document has changed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler<DocumentChangeEventArgs> Changed;
private event EventHandler<TextChangeEventArgs> TextChangedInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanged
{
add => TextChangedInternal += value;
remove => TextChangedInternal -= value;
}
/// <summary>
/// Creates a snapshot of the current text.
/// </summary>
/// <remarks>
/// <para>This method returns an immutable snapshot of the document, and may be safely called even when
/// the document's owner thread is concurrently modifying the document.
/// </para><para>
/// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other
/// classes implementing ITextSource.CreateSnapshot().
/// </para><para>
/// </para>
/// </remarks>
public ITextSource CreateSnapshot()
{
lock (_lockObject)
{
return new RopeTextSource(_rope, _versionProvider.CurrentVersion);
}
}
/// <summary>
/// Creates a snapshot of a part of the current text.
/// </summary>
/// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks>
public ITextSource CreateSnapshot(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextSource(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public ITextSourceVersion Version => _versionProvider.CurrentVersion;
/// <inheritdoc/>
public TextReader CreateReader()
{
lock (_lockObject)
{
return new RopeTextReader(_rope);
}
}
/// <inheritdoc/>
public TextReader CreateReader(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextReader(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer)
{
VerifyAccess();
_rope.WriteTo(writer, 0, _rope.Length);
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer, int offset, int length)
{
VerifyAccess();
_rope.WriteTo(writer, offset, length);
}
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region BeginUpdate / EndUpdate
private int _beginUpdateCount;
/// <summary>
/// Gets if an update is running.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public bool IsInUpdate
{
get
{
VerifyAccess();
return _beginUpdateCount > 0;
}
}
/// <summary>
/// Immediately calls <see cref="BeginUpdate()"/>,
/// and returns an IDisposable that calls <see cref="EndUpdate()"/>.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public IDisposable RunUpdate()
{
BeginUpdate();
return new CallbackOnDispose(EndUpdate);
}
/// <summary>
/// <para>Begins a group of document changes.</para>
/// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will
/// group all changes into a single action.</para>
/// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number
/// of EndUpdate calls the events resume their work.</para>
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void BeginUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot change document within another document change.");
_beginUpdateCount++;
if (_beginUpdateCount == 1)
{
_undoStack.StartUndoGroup();
UpdateStarted?.Invoke(this, EventArgs.Empty);
}
}
/// <summary>
/// Ends a group of document changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void EndUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot end update within document change.");
if (_beginUpdateCount == 0)
throw new InvalidOperationException("No update is active.");
if (_beginUpdateCount == 1)
{
// fire change events inside the change group - event handlers might add additional
// document changes to the change group
FireChangeEvents();
_undoStack.EndUndoGroup();
_beginUpdateCount = 0;
UpdateFinished?.Invoke(this, EventArgs.Empty);
}
else
{
_beginUpdateCount -= 1;
}
}
/// <summary>
/// Occurs when a document change starts.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateStarted;
/// <summary>
/// Occurs when a document change is finished.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateFinished;
void IDocument.StartUndoableAction()
{
BeginUpdate();
}
void IDocument.EndUndoableAction()
{
EndUpdate();
}
IDisposable IDocument.OpenUndoGroup()
{
return RunUpdate();
}
#endregion
#region Fire events after update
private int _oldTextLength;
private int _oldLineCount;
private bool _fireTextChanged;
/// <summary>
/// Fires TextChanged, TextLengthChanged, LineCountChanged if required.
/// </summary>
internal void FireChangeEvents()
{
// it may be necessary to fire the event multiple times if the document is changed
// from inside the event handlers
while (_fireTextChanged)
{
_fireTextChanged = false;
TextChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("Text");
var textLength = _rope.Length;
if (textLength != _oldTextLength)
{
_oldTextLength = textLength;
TextLengthChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("TextLength");
}
var lineCount = _lineTree.LineCount;
if (lineCount != _oldLineCount)
{
_oldLineCount = lineCount;
LineCountChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("LineCount");
}
}
}
#endregion
#region Insert / Remove / Replace
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, string text)
{
Replace(offset, 0, new StringTextSource(text), null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, ITextSource text)
{
Replace(offset, 0, text, null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, new StringTextSource(text), null);
}
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, text, null);
}
}
/// <summary>
/// Removes text.
/// </summary>
public void Remove(ISegment segment)
{
Replace(segment, string.Empty);
}
/// <summary>
/// Removes text.
/// </summary>
/// <param name="offset">Starting offset of the text to be removed.</param>
/// <param name="length">Length of the text to be removed.</param>
public void Remove(int offset, int length)
{
Replace(offset, length, StringTextSource.Empty);
}
internal bool InDocumentChanging;
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, string text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, ITextSource text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, string text)
{
Replace(offset, length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, ITextSource text)
{
Replace(offset, length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMappingType);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType)
{
if (text == null)
throw new ArgumentNullException(nameof(text));
// Please see OffsetChangeMappingType XML comments for details on how these modes work.
switch (offsetChangeMappingType)
{
case OffsetChangeMappingType.Normal:
Replace(offset, length, text, null);
break;
case OffsetChangeMappingType.KeepAnchorBeforeInsertion:
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(
new OffsetChangeMapEntry(offset, length, text.TextLength, false, true)));
break;
case OffsetChangeMappingType.RemoveAndInsert:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else
{
var map = new OffsetChangeMap(2)
{
new OffsetChangeMapEntry(offset, length, 0),
new OffsetChangeMapEntry(offset, 0, text.TextLength)
};
map.Freeze();
Replace(offset, length, text, map);
}
break;
case OffsetChangeMappingType.CharacterReplace:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else if (text.TextLength > length)
{
// look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace
// the last character
var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else if (text.TextLength < length)
{
var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else
{
Replace(offset, length, text, OffsetChangeMap.Empty);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value");
}
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMap);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap)
{
text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text));
offsetChangeMap?.Freeze();
// Ensure that all changes take place inside an update group.
// Will also take care of throwing an exception if inDocumentChanging is set.
BeginUpdate();
try
{
// protect document change against corruption by other changes inside the event handlers
InDocumentChanging = true;
try
{
// The range verification must wait until after the BeginUpdate() call because the document
// might be modified inside the UpdateStarted event.
ThrowIfRangeInvalid(offset, length);
DoReplace(offset, length, text, offsetChangeMap);
}
finally
{
InDocumentChanging = false;
}
}
finally
{
EndUpdate();
}
}
private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap)
{
if (length == 0 && newText.TextLength == 0)
return;
// trying to replace a single character in 'Normal' mode?
// for single characters, 'CharacterReplace' mode is equivalent, but more performant
// (we don't have to touch the anchorTree at all in 'CharacterReplace' mode)
if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null)
offsetChangeMap = OffsetChangeMap.Empty;
ITextSource removedText;
if (length == 0)
{
removedText = StringTextSource.Empty;
}
else if (length < 100)
{
removedText = new StringTextSource(_rope.ToString(offset, length));
}
else
{
// use a rope if the removed string is long
removedText = new RopeTextSource(_rope.GetRange(offset, length));
}
var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap);
// fire DocumentChanging event
Changing?.Invoke(this, args);
TextChangingInternal?.Invoke(this, args);
_undoStack.Push(this, args);
_cachedText = null; // reset cache of complete document text
_fireTextChanged = true;
var delayedEvents = new DelayedEvents();
lock (_lockObject)
{
// create linked list of checkpoints
_versionProvider.AppendChange(args);
// now update the textBuffer and lineTree
if (offset == 0 && length == _rope.Length)
{
// optimize replacing the whole document
_rope.Clear();
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(0, newRopeTextSource.GetRope());
else
_rope.InsertText(0, newText.Text);
_lineManager.Rebuild();
}
else
{
_rope.RemoveRange(offset, length);
_lineManager.Remove(offset, length);
#if DEBUG
_lineTree.CheckProperties();
#endif
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(offset, newRopeTextSource.GetRope());
else
_rope.InsertText(offset, newText.Text);
_lineManager.Insert(offset, newText);
#if DEBUG
_lineTree.CheckProperties();
#endif
}
}
// update text anchors
if (offsetChangeMap == null)
{
_anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents);
}
else
{
foreach (var entry in offsetChangeMap)
{
_anchorTree.HandleTextChange(entry, delayedEvents);
}
}
_lineManager.ChangeComplete(args);
// raise delayed events after our data structures are consistent again
delayedEvents.RaiseEvents();
// fire DocumentChanged event
Changed?.Invoke(this, args);
TextChangedInternal?.Invoke(this, args);
}
#endregion
#region GetLineBy...
/// <summary>
/// Gets a read-only list of lines.
/// </summary>
/// <remarks><inheritdoc cref="DocumentLine"/></remarks>
public IList<DocumentLine> Lines => _lineTree;
/// <summary>
/// Gets a line by the line number: O(log n)
/// </summary>
public DocumentLine GetLineByNumber(int number)
{
VerifyAccess();
if (number < 1 || number > _lineTree.LineCount)
throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount);
return _lineTree.GetByNumber(number);
}
IDocumentLine IDocument.GetLineByNumber(int lineNumber)
{
return GetLineByNumber(lineNumber);
}
/// <summary>
/// Gets a document lines by offset.
/// Runtime: O(log n)
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")]
public DocumentLine GetLineByOffset(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length);
}
return _lineTree.GetByOffset(offset);
}
IDocumentLine IDocument.GetLineByOffset(int offset)
{
return GetLineByOffset(offset);
}
#endregion
#region GetOffset / GetLocation
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(TextLocation location)
{
return GetOffset(location.Line, location.Column);
}
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(int line, int column)
{
var docLine = GetLineByNumber(line);
if (column <= 0)
return docLine.Offset;
if (column > docLine.Length)
return docLine.EndOffset;
return docLine.Offset + column - 1;
}
/// <summary>
/// Gets the location from an offset.
/// </summary>
/// <seealso cref="GetOffset(TextLocation)"/>
public TextLocation GetLocation(int offset)
{
var line = GetLineByOffset(offset);
return new TextLocation(line.LineNumber, offset - line.Offset + 1);
}
#endregion
#region Line Trackers
private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>();
/// <summary>
/// Gets the list of <see cref="ILineTracker"/>s attached to this document.
/// You can add custom line trackers to this list.
/// </summary>
public IList<ILineTracker> LineTrackers
{
get
{
VerifyAccess();
return _lineTrackers;
}
}
#endregion
#region UndoStack
public UndoStack _undoStack;
/// <summary>
/// Gets the <see cref="UndoStack"/> of the document.
/// </summary>
/// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks>
public UndoStack UndoStack
{
get => _undoStack;
set
{
if (value == null)
throw new ArgumentNullException();
if (value != _undoStack)
{
_undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document
// ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress)
_undoStack = value;
OnPropertyChanged("UndoStack");
}
}
}
#endregion
#region CreateAnchor
/// <summary>
/// Creates a new <see cref="TextAnchor"/> at the specified offset.
/// </summary>
/// <inheritdoc cref="TextAnchor" select="remarks|example"/>
public TextAnchor CreateAnchor(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
return _anchorTree.CreateAnchor(offset);
}
ITextAnchor IDocument.CreateAnchor(int offset)
{
return CreateAnchor(offset);
}
#endregion
#region LineCount
/// <summary>
/// Gets the total number of lines in the document.
/// Runtime: O(1).
/// </summary>
public int LineCount
{
get
{
VerifyAccess();
return _lineTree.LineCount;
}
}
/// <summary>
/// Is raised when the LineCount property changes.
/// </summary>
public event EventHandler LineCountChanged;
#endregion
#region Debugging
[Conditional("DEBUG")]
internal void DebugVerifyAccess()
{
VerifyAccess();
}
/// <summary>
/// Gets the document lines tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetLineTreeAsString()
{
#if DEBUG
return _lineTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
/// <summary>
/// Gets the text anchor tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetTextAnchorTreeAsString()
{
#if DEBUG
return _anchorTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
#endregion
#region Service Provider
private IServiceProvider _serviceProvider;
internal IServiceProvider ServiceProvider
{
get
{
VerifyAccess();
if (_serviceProvider == null)
{
var container = new ServiceContainer();
container.AddService(this);
container.AddService<IDocument>(this);
_serviceProvider = container;
}
return _serviceProvider;
}
set
{
VerifyAccess();
_serviceProvider = value ?? throw new ArgumentNullException(nameof(value));
}
}
object IServiceProvider.GetService(Type serviceType)
{
return ServiceProvider.GetService(serviceType);
}
#endregion
#region FileName
private string _fileName;
/// <inheritdoc/>
public event EventHandler FileNameChanged;
private void OnFileNameChanged(EventArgs e)
{
FileNameChanged?.Invoke(this, e);
}
/// <inheritdoc/>
public string FileName
{
get { return _fileName; }
set
{
if (_fileName != value)
{
_fileName = value;
OnFileNameChanged(EventArgs.Empty);
}
}
}
#endregion
}
}
<MSG> Merge pull request #51 from danwalmsley/fix-thread-verification
verify access checks against thread textdocument is created on.
<DFF> @@ -26,6 +26,7 @@ using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
+using System.Threading;
namespace AvaloniaEdit.Document
{
@@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document
return _rope.ToString(offset, length);
}
+ private Thread ownerThread = Thread.CurrentThread;
+
private void VerifyAccess()
{
- Dispatcher.UIThread.VerifyAccess();
+ if(Thread.CurrentThread != ownerThread)
+ {
+ throw new InvalidOperationException("Call from invalid thread.");
+ }
}
/// <summary>
| 7 | Merge pull request #51 from danwalmsley/fix-thread-verification | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059875 | <NME> TextDocument.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
namespace AvaloniaEdit.Document
{
/// <summary>
/// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events.
/// </summary>
/// <remarks>
/// <b>Thread safety:</b>
/// <inheritdoc cref="VerifyAccess"/>
/// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para>
/// </remarks>
public sealed class TextDocument : IDocument, INotifyPropertyChanged
{
#region Thread ownership
private readonly object _lockObject = new object();
#endregion
#region Fields + Constructor
private readonly Rope<char> _rope;
private readonly DocumentLineTree _lineTree;
private readonly LineManager _lineManager;
private readonly TextAnchorTree _anchorTree;
private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider();
/// <summary>
/// Create an empty text document.
/// </summary>
public TextDocument()
: this(string.Empty.ToCharArray())
{
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(IEnumerable<char> initialText)
{
if (initialText == null)
throw new ArgumentNullException(nameof(initialText));
_rope = new Rope<char>(initialText);
_lineTree = new DocumentLineTree(this);
_lineManager = new LineManager(_lineTree, this);
_lineTrackers.CollectionChanged += delegate
{
_lineManager.UpdateListOfLineTrackers();
};
_anchorTree = new TextAnchorTree(this);
_undoStack = new UndoStack();
FireChangeEvents();
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(ITextSource initialText)
: this(GetTextFromTextSource(initialText))
{
}
// gets the text from a text source, directly retrieving the underlying rope where possible
private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource)
{
if (textSource == null)
throw new ArgumentNullException(nameof(textSource));
if (textSource is RopeTextSource rts)
{
return rts.GetRope();
}
if (textSource is TextDocument doc)
{
return doc._rope;
}
return textSource.Text.ToCharArray();
}
#endregion
#region Text
private void ThrowIfRangeInvalid(int offset, int length)
{
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
if (length < 0 || offset + length > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
}
/// <inheritdoc/>
public string GetText(int offset, int length)
{
VerifyAccess();
return _rope.ToString(offset, length);
}
private void VerifyAccess()
{
Dispatcher.UIThread.VerifyAccess();
}
/// <summary>
public void SetOwnerThread(Thread newOwner)
{
// We need to lock here to ensure that in the null owner case,
// only one thread succeeds in taking ownership.
lock (_lockObject) {
if (ownerThread != null) {
VerifyAccess();
}
ownerThread = newOwner;
}
}
private void VerifyAccess()
{
if(Thread.CurrentThread != ownerThread)
{
throw new InvalidOperationException("Call from invalid thread.");
}
}
/// <summary>
/// Retrieves the text for a portion of the document.
/// </summary>
public string GetText(ISegment segment)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
return GetText(segment.Offset, segment.Length);
}
/// <inheritdoc/>
public int IndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.IndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int LastIndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.LastIndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int IndexOfAny(char[] anyOf, int startIndex, int count)
{
DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds
return _rope.IndexOfAny(anyOf, startIndex, count);
}
/// <inheritdoc/>
public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.IndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.LastIndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public char GetCharAt(int offset)
{
DebugVerifyAccess(); // frequently called, so must be fast in release builds
return _rope[offset];
}
private WeakReference _cachedText;
/// <summary>
/// Gets/Sets the text of the whole document.
/// </summary>
public string Text
{
get
{
VerifyAccess();
var completeText = _cachedText?.Target as string;
if (completeText == null)
{
completeText = _rope.ToString();
_cachedText = new WeakReference(completeText);
}
return completeText;
}
set
{
VerifyAccess();
if (value == null)
throw new ArgumentNullException(nameof(value));
Replace(0, _rope.Length, value);
}
}
/// <summary>
/// This event is called after a group of changes is completed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextChanged;
event EventHandler IDocument.ChangeCompleted
{
add => TextChanged += value;
remove => TextChanged -= value;
}
/// <inheritdoc/>
public int TextLength
{
get
{
VerifyAccess();
return _rope.Length;
}
}
/// <summary>
/// Is raised when the TextLength property changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextLengthChanged;
/// <summary>
/// Is raised before the document changes.
/// </summary>
/// <remarks>
/// <para>Here is the order in which events are raised during a document update:</para>
/// <list type="bullet">
/// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description>Start of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateStarted"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="Changing"/> event is raised</description></item>
/// <item><description>The document is changed</description></item>
/// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were
/// in the deleted text portion</description></item>
/// <item><description><see cref="Changed"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="TextChanged"/> event is raised</description></item>
/// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item>
/// <item><description>End of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateFinished"/> event is raised</description></item>
/// </list></item>
/// </list>
/// <para>
/// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>,
/// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>.
/// </para><para>
/// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls.
/// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done.
/// </para><para>
/// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step.
/// </para>
/// </remarks>
public event EventHandler<DocumentChangeEventArgs> Changing;
// Unfortunately EventHandler<T> is invariant, so we have to use two separate events
private event EventHandler<TextChangeEventArgs> TextChangingInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanging
{
add => TextChangingInternal += value;
remove => TextChangingInternal -= value;
}
/// <summary>
/// Is raised after the document has changed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler<DocumentChangeEventArgs> Changed;
private event EventHandler<TextChangeEventArgs> TextChangedInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanged
{
add => TextChangedInternal += value;
remove => TextChangedInternal -= value;
}
/// <summary>
/// Creates a snapshot of the current text.
/// </summary>
/// <remarks>
/// <para>This method returns an immutable snapshot of the document, and may be safely called even when
/// the document's owner thread is concurrently modifying the document.
/// </para><para>
/// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other
/// classes implementing ITextSource.CreateSnapshot().
/// </para><para>
/// </para>
/// </remarks>
public ITextSource CreateSnapshot()
{
lock (_lockObject)
{
return new RopeTextSource(_rope, _versionProvider.CurrentVersion);
}
}
/// <summary>
/// Creates a snapshot of a part of the current text.
/// </summary>
/// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks>
public ITextSource CreateSnapshot(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextSource(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public ITextSourceVersion Version => _versionProvider.CurrentVersion;
/// <inheritdoc/>
public TextReader CreateReader()
{
lock (_lockObject)
{
return new RopeTextReader(_rope);
}
}
/// <inheritdoc/>
public TextReader CreateReader(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextReader(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer)
{
VerifyAccess();
_rope.WriteTo(writer, 0, _rope.Length);
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer, int offset, int length)
{
VerifyAccess();
_rope.WriteTo(writer, offset, length);
}
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region BeginUpdate / EndUpdate
private int _beginUpdateCount;
/// <summary>
/// Gets if an update is running.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public bool IsInUpdate
{
get
{
VerifyAccess();
return _beginUpdateCount > 0;
}
}
/// <summary>
/// Immediately calls <see cref="BeginUpdate()"/>,
/// and returns an IDisposable that calls <see cref="EndUpdate()"/>.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public IDisposable RunUpdate()
{
BeginUpdate();
return new CallbackOnDispose(EndUpdate);
}
/// <summary>
/// <para>Begins a group of document changes.</para>
/// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will
/// group all changes into a single action.</para>
/// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number
/// of EndUpdate calls the events resume their work.</para>
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void BeginUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot change document within another document change.");
_beginUpdateCount++;
if (_beginUpdateCount == 1)
{
_undoStack.StartUndoGroup();
UpdateStarted?.Invoke(this, EventArgs.Empty);
}
}
/// <summary>
/// Ends a group of document changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void EndUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot end update within document change.");
if (_beginUpdateCount == 0)
throw new InvalidOperationException("No update is active.");
if (_beginUpdateCount == 1)
{
// fire change events inside the change group - event handlers might add additional
// document changes to the change group
FireChangeEvents();
_undoStack.EndUndoGroup();
_beginUpdateCount = 0;
UpdateFinished?.Invoke(this, EventArgs.Empty);
}
else
{
_beginUpdateCount -= 1;
}
}
/// <summary>
/// Occurs when a document change starts.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateStarted;
/// <summary>
/// Occurs when a document change is finished.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateFinished;
void IDocument.StartUndoableAction()
{
BeginUpdate();
}
void IDocument.EndUndoableAction()
{
EndUpdate();
}
IDisposable IDocument.OpenUndoGroup()
{
return RunUpdate();
}
#endregion
#region Fire events after update
private int _oldTextLength;
private int _oldLineCount;
private bool _fireTextChanged;
/// <summary>
/// Fires TextChanged, TextLengthChanged, LineCountChanged if required.
/// </summary>
internal void FireChangeEvents()
{
// it may be necessary to fire the event multiple times if the document is changed
// from inside the event handlers
while (_fireTextChanged)
{
_fireTextChanged = false;
TextChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("Text");
var textLength = _rope.Length;
if (textLength != _oldTextLength)
{
_oldTextLength = textLength;
TextLengthChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("TextLength");
}
var lineCount = _lineTree.LineCount;
if (lineCount != _oldLineCount)
{
_oldLineCount = lineCount;
LineCountChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("LineCount");
}
}
}
#endregion
#region Insert / Remove / Replace
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, string text)
{
Replace(offset, 0, new StringTextSource(text), null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, ITextSource text)
{
Replace(offset, 0, text, null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, new StringTextSource(text), null);
}
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, text, null);
}
}
/// <summary>
/// Removes text.
/// </summary>
public void Remove(ISegment segment)
{
Replace(segment, string.Empty);
}
/// <summary>
/// Removes text.
/// </summary>
/// <param name="offset">Starting offset of the text to be removed.</param>
/// <param name="length">Length of the text to be removed.</param>
public void Remove(int offset, int length)
{
Replace(offset, length, StringTextSource.Empty);
}
internal bool InDocumentChanging;
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, string text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, ITextSource text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, string text)
{
Replace(offset, length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, ITextSource text)
{
Replace(offset, length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMappingType);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType)
{
if (text == null)
throw new ArgumentNullException(nameof(text));
// Please see OffsetChangeMappingType XML comments for details on how these modes work.
switch (offsetChangeMappingType)
{
case OffsetChangeMappingType.Normal:
Replace(offset, length, text, null);
break;
case OffsetChangeMappingType.KeepAnchorBeforeInsertion:
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(
new OffsetChangeMapEntry(offset, length, text.TextLength, false, true)));
break;
case OffsetChangeMappingType.RemoveAndInsert:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else
{
var map = new OffsetChangeMap(2)
{
new OffsetChangeMapEntry(offset, length, 0),
new OffsetChangeMapEntry(offset, 0, text.TextLength)
};
map.Freeze();
Replace(offset, length, text, map);
}
break;
case OffsetChangeMappingType.CharacterReplace:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else if (text.TextLength > length)
{
// look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace
// the last character
var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else if (text.TextLength < length)
{
var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else
{
Replace(offset, length, text, OffsetChangeMap.Empty);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value");
}
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMap);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap)
{
text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text));
offsetChangeMap?.Freeze();
// Ensure that all changes take place inside an update group.
// Will also take care of throwing an exception if inDocumentChanging is set.
BeginUpdate();
try
{
// protect document change against corruption by other changes inside the event handlers
InDocumentChanging = true;
try
{
// The range verification must wait until after the BeginUpdate() call because the document
// might be modified inside the UpdateStarted event.
ThrowIfRangeInvalid(offset, length);
DoReplace(offset, length, text, offsetChangeMap);
}
finally
{
InDocumentChanging = false;
}
}
finally
{
EndUpdate();
}
}
private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap)
{
if (length == 0 && newText.TextLength == 0)
return;
// trying to replace a single character in 'Normal' mode?
// for single characters, 'CharacterReplace' mode is equivalent, but more performant
// (we don't have to touch the anchorTree at all in 'CharacterReplace' mode)
if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null)
offsetChangeMap = OffsetChangeMap.Empty;
ITextSource removedText;
if (length == 0)
{
removedText = StringTextSource.Empty;
}
else if (length < 100)
{
removedText = new StringTextSource(_rope.ToString(offset, length));
}
else
{
// use a rope if the removed string is long
removedText = new RopeTextSource(_rope.GetRange(offset, length));
}
var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap);
// fire DocumentChanging event
Changing?.Invoke(this, args);
TextChangingInternal?.Invoke(this, args);
_undoStack.Push(this, args);
_cachedText = null; // reset cache of complete document text
_fireTextChanged = true;
var delayedEvents = new DelayedEvents();
lock (_lockObject)
{
// create linked list of checkpoints
_versionProvider.AppendChange(args);
// now update the textBuffer and lineTree
if (offset == 0 && length == _rope.Length)
{
// optimize replacing the whole document
_rope.Clear();
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(0, newRopeTextSource.GetRope());
else
_rope.InsertText(0, newText.Text);
_lineManager.Rebuild();
}
else
{
_rope.RemoveRange(offset, length);
_lineManager.Remove(offset, length);
#if DEBUG
_lineTree.CheckProperties();
#endif
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(offset, newRopeTextSource.GetRope());
else
_rope.InsertText(offset, newText.Text);
_lineManager.Insert(offset, newText);
#if DEBUG
_lineTree.CheckProperties();
#endif
}
}
// update text anchors
if (offsetChangeMap == null)
{
_anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents);
}
else
{
foreach (var entry in offsetChangeMap)
{
_anchorTree.HandleTextChange(entry, delayedEvents);
}
}
_lineManager.ChangeComplete(args);
// raise delayed events after our data structures are consistent again
delayedEvents.RaiseEvents();
// fire DocumentChanged event
Changed?.Invoke(this, args);
TextChangedInternal?.Invoke(this, args);
}
#endregion
#region GetLineBy...
/// <summary>
/// Gets a read-only list of lines.
/// </summary>
/// <remarks><inheritdoc cref="DocumentLine"/></remarks>
public IList<DocumentLine> Lines => _lineTree;
/// <summary>
/// Gets a line by the line number: O(log n)
/// </summary>
public DocumentLine GetLineByNumber(int number)
{
VerifyAccess();
if (number < 1 || number > _lineTree.LineCount)
throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount);
return _lineTree.GetByNumber(number);
}
IDocumentLine IDocument.GetLineByNumber(int lineNumber)
{
return GetLineByNumber(lineNumber);
}
/// <summary>
/// Gets a document lines by offset.
/// Runtime: O(log n)
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")]
public DocumentLine GetLineByOffset(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length);
}
return _lineTree.GetByOffset(offset);
}
IDocumentLine IDocument.GetLineByOffset(int offset)
{
return GetLineByOffset(offset);
}
#endregion
#region GetOffset / GetLocation
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(TextLocation location)
{
return GetOffset(location.Line, location.Column);
}
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(int line, int column)
{
var docLine = GetLineByNumber(line);
if (column <= 0)
return docLine.Offset;
if (column > docLine.Length)
return docLine.EndOffset;
return docLine.Offset + column - 1;
}
/// <summary>
/// Gets the location from an offset.
/// </summary>
/// <seealso cref="GetOffset(TextLocation)"/>
public TextLocation GetLocation(int offset)
{
var line = GetLineByOffset(offset);
return new TextLocation(line.LineNumber, offset - line.Offset + 1);
}
#endregion
#region Line Trackers
private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>();
/// <summary>
/// Gets the list of <see cref="ILineTracker"/>s attached to this document.
/// You can add custom line trackers to this list.
/// </summary>
public IList<ILineTracker> LineTrackers
{
get
{
VerifyAccess();
return _lineTrackers;
}
}
#endregion
#region UndoStack
public UndoStack _undoStack;
/// <summary>
/// Gets the <see cref="UndoStack"/> of the document.
/// </summary>
/// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks>
public UndoStack UndoStack
{
get => _undoStack;
set
{
if (value == null)
throw new ArgumentNullException();
if (value != _undoStack)
{
_undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document
// ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress)
_undoStack = value;
OnPropertyChanged("UndoStack");
}
}
}
#endregion
#region CreateAnchor
/// <summary>
/// Creates a new <see cref="TextAnchor"/> at the specified offset.
/// </summary>
/// <inheritdoc cref="TextAnchor" select="remarks|example"/>
public TextAnchor CreateAnchor(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
return _anchorTree.CreateAnchor(offset);
}
ITextAnchor IDocument.CreateAnchor(int offset)
{
return CreateAnchor(offset);
}
#endregion
#region LineCount
/// <summary>
/// Gets the total number of lines in the document.
/// Runtime: O(1).
/// </summary>
public int LineCount
{
get
{
VerifyAccess();
return _lineTree.LineCount;
}
}
/// <summary>
/// Is raised when the LineCount property changes.
/// </summary>
public event EventHandler LineCountChanged;
#endregion
#region Debugging
[Conditional("DEBUG")]
internal void DebugVerifyAccess()
{
VerifyAccess();
}
/// <summary>
/// Gets the document lines tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetLineTreeAsString()
{
#if DEBUG
return _lineTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
/// <summary>
/// Gets the text anchor tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetTextAnchorTreeAsString()
{
#if DEBUG
return _anchorTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
#endregion
#region Service Provider
private IServiceProvider _serviceProvider;
internal IServiceProvider ServiceProvider
{
get
{
VerifyAccess();
if (_serviceProvider == null)
{
var container = new ServiceContainer();
container.AddService(this);
container.AddService<IDocument>(this);
_serviceProvider = container;
}
return _serviceProvider;
}
set
{
VerifyAccess();
_serviceProvider = value ?? throw new ArgumentNullException(nameof(value));
}
}
object IServiceProvider.GetService(Type serviceType)
{
return ServiceProvider.GetService(serviceType);
}
#endregion
#region FileName
private string _fileName;
/// <inheritdoc/>
public event EventHandler FileNameChanged;
private void OnFileNameChanged(EventArgs e)
{
FileNameChanged?.Invoke(this, e);
}
/// <inheritdoc/>
public string FileName
{
get { return _fileName; }
set
{
if (_fileName != value)
{
_fileName = value;
OnFileNameChanged(EventArgs.Empty);
}
}
}
#endregion
}
}
<MSG> Merge pull request #51 from danwalmsley/fix-thread-verification
verify access checks against thread textdocument is created on.
<DFF> @@ -26,6 +26,7 @@ using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
+using System.Threading;
namespace AvaloniaEdit.Document
{
@@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document
return _rope.ToString(offset, length);
}
+ private Thread ownerThread = Thread.CurrentThread;
+
private void VerifyAccess()
{
- Dispatcher.UIThread.VerifyAccess();
+ if(Thread.CurrentThread != ownerThread)
+ {
+ throw new InvalidOperationException("Call from invalid thread.");
+ }
}
/// <summary>
| 7 | Merge pull request #51 from danwalmsley/fix-thread-verification | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059876 | <NME> TextDocument.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
namespace AvaloniaEdit.Document
{
/// <summary>
/// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events.
/// </summary>
/// <remarks>
/// <b>Thread safety:</b>
/// <inheritdoc cref="VerifyAccess"/>
/// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para>
/// </remarks>
public sealed class TextDocument : IDocument, INotifyPropertyChanged
{
#region Thread ownership
private readonly object _lockObject = new object();
#endregion
#region Fields + Constructor
private readonly Rope<char> _rope;
private readonly DocumentLineTree _lineTree;
private readonly LineManager _lineManager;
private readonly TextAnchorTree _anchorTree;
private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider();
/// <summary>
/// Create an empty text document.
/// </summary>
public TextDocument()
: this(string.Empty.ToCharArray())
{
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(IEnumerable<char> initialText)
{
if (initialText == null)
throw new ArgumentNullException(nameof(initialText));
_rope = new Rope<char>(initialText);
_lineTree = new DocumentLineTree(this);
_lineManager = new LineManager(_lineTree, this);
_lineTrackers.CollectionChanged += delegate
{
_lineManager.UpdateListOfLineTrackers();
};
_anchorTree = new TextAnchorTree(this);
_undoStack = new UndoStack();
FireChangeEvents();
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(ITextSource initialText)
: this(GetTextFromTextSource(initialText))
{
}
// gets the text from a text source, directly retrieving the underlying rope where possible
private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource)
{
if (textSource == null)
throw new ArgumentNullException(nameof(textSource));
if (textSource is RopeTextSource rts)
{
return rts.GetRope();
}
if (textSource is TextDocument doc)
{
return doc._rope;
}
return textSource.Text.ToCharArray();
}
#endregion
#region Text
private void ThrowIfRangeInvalid(int offset, int length)
{
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
if (length < 0 || offset + length > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
}
/// <inheritdoc/>
public string GetText(int offset, int length)
{
VerifyAccess();
return _rope.ToString(offset, length);
}
private void VerifyAccess()
{
Dispatcher.UIThread.VerifyAccess();
}
/// <summary>
public void SetOwnerThread(Thread newOwner)
{
// We need to lock here to ensure that in the null owner case,
// only one thread succeeds in taking ownership.
lock (_lockObject) {
if (ownerThread != null) {
VerifyAccess();
}
ownerThread = newOwner;
}
}
private void VerifyAccess()
{
if(Thread.CurrentThread != ownerThread)
{
throw new InvalidOperationException("Call from invalid thread.");
}
}
/// <summary>
/// Retrieves the text for a portion of the document.
/// </summary>
public string GetText(ISegment segment)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
return GetText(segment.Offset, segment.Length);
}
/// <inheritdoc/>
public int IndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.IndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int LastIndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.LastIndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int IndexOfAny(char[] anyOf, int startIndex, int count)
{
DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds
return _rope.IndexOfAny(anyOf, startIndex, count);
}
/// <inheritdoc/>
public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.IndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.LastIndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public char GetCharAt(int offset)
{
DebugVerifyAccess(); // frequently called, so must be fast in release builds
return _rope[offset];
}
private WeakReference _cachedText;
/// <summary>
/// Gets/Sets the text of the whole document.
/// </summary>
public string Text
{
get
{
VerifyAccess();
var completeText = _cachedText?.Target as string;
if (completeText == null)
{
completeText = _rope.ToString();
_cachedText = new WeakReference(completeText);
}
return completeText;
}
set
{
VerifyAccess();
if (value == null)
throw new ArgumentNullException(nameof(value));
Replace(0, _rope.Length, value);
}
}
/// <summary>
/// This event is called after a group of changes is completed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextChanged;
event EventHandler IDocument.ChangeCompleted
{
add => TextChanged += value;
remove => TextChanged -= value;
}
/// <inheritdoc/>
public int TextLength
{
get
{
VerifyAccess();
return _rope.Length;
}
}
/// <summary>
/// Is raised when the TextLength property changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextLengthChanged;
/// <summary>
/// Is raised before the document changes.
/// </summary>
/// <remarks>
/// <para>Here is the order in which events are raised during a document update:</para>
/// <list type="bullet">
/// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description>Start of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateStarted"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="Changing"/> event is raised</description></item>
/// <item><description>The document is changed</description></item>
/// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were
/// in the deleted text portion</description></item>
/// <item><description><see cref="Changed"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="TextChanged"/> event is raised</description></item>
/// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item>
/// <item><description>End of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateFinished"/> event is raised</description></item>
/// </list></item>
/// </list>
/// <para>
/// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>,
/// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>.
/// </para><para>
/// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls.
/// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done.
/// </para><para>
/// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step.
/// </para>
/// </remarks>
public event EventHandler<DocumentChangeEventArgs> Changing;
// Unfortunately EventHandler<T> is invariant, so we have to use two separate events
private event EventHandler<TextChangeEventArgs> TextChangingInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanging
{
add => TextChangingInternal += value;
remove => TextChangingInternal -= value;
}
/// <summary>
/// Is raised after the document has changed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler<DocumentChangeEventArgs> Changed;
private event EventHandler<TextChangeEventArgs> TextChangedInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanged
{
add => TextChangedInternal += value;
remove => TextChangedInternal -= value;
}
/// <summary>
/// Creates a snapshot of the current text.
/// </summary>
/// <remarks>
/// <para>This method returns an immutable snapshot of the document, and may be safely called even when
/// the document's owner thread is concurrently modifying the document.
/// </para><para>
/// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other
/// classes implementing ITextSource.CreateSnapshot().
/// </para><para>
/// </para>
/// </remarks>
public ITextSource CreateSnapshot()
{
lock (_lockObject)
{
return new RopeTextSource(_rope, _versionProvider.CurrentVersion);
}
}
/// <summary>
/// Creates a snapshot of a part of the current text.
/// </summary>
/// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks>
public ITextSource CreateSnapshot(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextSource(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public ITextSourceVersion Version => _versionProvider.CurrentVersion;
/// <inheritdoc/>
public TextReader CreateReader()
{
lock (_lockObject)
{
return new RopeTextReader(_rope);
}
}
/// <inheritdoc/>
public TextReader CreateReader(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextReader(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer)
{
VerifyAccess();
_rope.WriteTo(writer, 0, _rope.Length);
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer, int offset, int length)
{
VerifyAccess();
_rope.WriteTo(writer, offset, length);
}
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region BeginUpdate / EndUpdate
private int _beginUpdateCount;
/// <summary>
/// Gets if an update is running.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public bool IsInUpdate
{
get
{
VerifyAccess();
return _beginUpdateCount > 0;
}
}
/// <summary>
/// Immediately calls <see cref="BeginUpdate()"/>,
/// and returns an IDisposable that calls <see cref="EndUpdate()"/>.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public IDisposable RunUpdate()
{
BeginUpdate();
return new CallbackOnDispose(EndUpdate);
}
/// <summary>
/// <para>Begins a group of document changes.</para>
/// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will
/// group all changes into a single action.</para>
/// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number
/// of EndUpdate calls the events resume their work.</para>
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void BeginUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot change document within another document change.");
_beginUpdateCount++;
if (_beginUpdateCount == 1)
{
_undoStack.StartUndoGroup();
UpdateStarted?.Invoke(this, EventArgs.Empty);
}
}
/// <summary>
/// Ends a group of document changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void EndUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot end update within document change.");
if (_beginUpdateCount == 0)
throw new InvalidOperationException("No update is active.");
if (_beginUpdateCount == 1)
{
// fire change events inside the change group - event handlers might add additional
// document changes to the change group
FireChangeEvents();
_undoStack.EndUndoGroup();
_beginUpdateCount = 0;
UpdateFinished?.Invoke(this, EventArgs.Empty);
}
else
{
_beginUpdateCount -= 1;
}
}
/// <summary>
/// Occurs when a document change starts.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateStarted;
/// <summary>
/// Occurs when a document change is finished.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateFinished;
void IDocument.StartUndoableAction()
{
BeginUpdate();
}
void IDocument.EndUndoableAction()
{
EndUpdate();
}
IDisposable IDocument.OpenUndoGroup()
{
return RunUpdate();
}
#endregion
#region Fire events after update
private int _oldTextLength;
private int _oldLineCount;
private bool _fireTextChanged;
/// <summary>
/// Fires TextChanged, TextLengthChanged, LineCountChanged if required.
/// </summary>
internal void FireChangeEvents()
{
// it may be necessary to fire the event multiple times if the document is changed
// from inside the event handlers
while (_fireTextChanged)
{
_fireTextChanged = false;
TextChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("Text");
var textLength = _rope.Length;
if (textLength != _oldTextLength)
{
_oldTextLength = textLength;
TextLengthChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("TextLength");
}
var lineCount = _lineTree.LineCount;
if (lineCount != _oldLineCount)
{
_oldLineCount = lineCount;
LineCountChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("LineCount");
}
}
}
#endregion
#region Insert / Remove / Replace
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, string text)
{
Replace(offset, 0, new StringTextSource(text), null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, ITextSource text)
{
Replace(offset, 0, text, null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, new StringTextSource(text), null);
}
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, text, null);
}
}
/// <summary>
/// Removes text.
/// </summary>
public void Remove(ISegment segment)
{
Replace(segment, string.Empty);
}
/// <summary>
/// Removes text.
/// </summary>
/// <param name="offset">Starting offset of the text to be removed.</param>
/// <param name="length">Length of the text to be removed.</param>
public void Remove(int offset, int length)
{
Replace(offset, length, StringTextSource.Empty);
}
internal bool InDocumentChanging;
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, string text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, ITextSource text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, string text)
{
Replace(offset, length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, ITextSource text)
{
Replace(offset, length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMappingType);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType)
{
if (text == null)
throw new ArgumentNullException(nameof(text));
// Please see OffsetChangeMappingType XML comments for details on how these modes work.
switch (offsetChangeMappingType)
{
case OffsetChangeMappingType.Normal:
Replace(offset, length, text, null);
break;
case OffsetChangeMappingType.KeepAnchorBeforeInsertion:
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(
new OffsetChangeMapEntry(offset, length, text.TextLength, false, true)));
break;
case OffsetChangeMappingType.RemoveAndInsert:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else
{
var map = new OffsetChangeMap(2)
{
new OffsetChangeMapEntry(offset, length, 0),
new OffsetChangeMapEntry(offset, 0, text.TextLength)
};
map.Freeze();
Replace(offset, length, text, map);
}
break;
case OffsetChangeMappingType.CharacterReplace:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else if (text.TextLength > length)
{
// look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace
// the last character
var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else if (text.TextLength < length)
{
var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else
{
Replace(offset, length, text, OffsetChangeMap.Empty);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value");
}
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMap);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap)
{
text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text));
offsetChangeMap?.Freeze();
// Ensure that all changes take place inside an update group.
// Will also take care of throwing an exception if inDocumentChanging is set.
BeginUpdate();
try
{
// protect document change against corruption by other changes inside the event handlers
InDocumentChanging = true;
try
{
// The range verification must wait until after the BeginUpdate() call because the document
// might be modified inside the UpdateStarted event.
ThrowIfRangeInvalid(offset, length);
DoReplace(offset, length, text, offsetChangeMap);
}
finally
{
InDocumentChanging = false;
}
}
finally
{
EndUpdate();
}
}
private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap)
{
if (length == 0 && newText.TextLength == 0)
return;
// trying to replace a single character in 'Normal' mode?
// for single characters, 'CharacterReplace' mode is equivalent, but more performant
// (we don't have to touch the anchorTree at all in 'CharacterReplace' mode)
if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null)
offsetChangeMap = OffsetChangeMap.Empty;
ITextSource removedText;
if (length == 0)
{
removedText = StringTextSource.Empty;
}
else if (length < 100)
{
removedText = new StringTextSource(_rope.ToString(offset, length));
}
else
{
// use a rope if the removed string is long
removedText = new RopeTextSource(_rope.GetRange(offset, length));
}
var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap);
// fire DocumentChanging event
Changing?.Invoke(this, args);
TextChangingInternal?.Invoke(this, args);
_undoStack.Push(this, args);
_cachedText = null; // reset cache of complete document text
_fireTextChanged = true;
var delayedEvents = new DelayedEvents();
lock (_lockObject)
{
// create linked list of checkpoints
_versionProvider.AppendChange(args);
// now update the textBuffer and lineTree
if (offset == 0 && length == _rope.Length)
{
// optimize replacing the whole document
_rope.Clear();
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(0, newRopeTextSource.GetRope());
else
_rope.InsertText(0, newText.Text);
_lineManager.Rebuild();
}
else
{
_rope.RemoveRange(offset, length);
_lineManager.Remove(offset, length);
#if DEBUG
_lineTree.CheckProperties();
#endif
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(offset, newRopeTextSource.GetRope());
else
_rope.InsertText(offset, newText.Text);
_lineManager.Insert(offset, newText);
#if DEBUG
_lineTree.CheckProperties();
#endif
}
}
// update text anchors
if (offsetChangeMap == null)
{
_anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents);
}
else
{
foreach (var entry in offsetChangeMap)
{
_anchorTree.HandleTextChange(entry, delayedEvents);
}
}
_lineManager.ChangeComplete(args);
// raise delayed events after our data structures are consistent again
delayedEvents.RaiseEvents();
// fire DocumentChanged event
Changed?.Invoke(this, args);
TextChangedInternal?.Invoke(this, args);
}
#endregion
#region GetLineBy...
/// <summary>
/// Gets a read-only list of lines.
/// </summary>
/// <remarks><inheritdoc cref="DocumentLine"/></remarks>
public IList<DocumentLine> Lines => _lineTree;
/// <summary>
/// Gets a line by the line number: O(log n)
/// </summary>
public DocumentLine GetLineByNumber(int number)
{
VerifyAccess();
if (number < 1 || number > _lineTree.LineCount)
throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount);
return _lineTree.GetByNumber(number);
}
IDocumentLine IDocument.GetLineByNumber(int lineNumber)
{
return GetLineByNumber(lineNumber);
}
/// <summary>
/// Gets a document lines by offset.
/// Runtime: O(log n)
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")]
public DocumentLine GetLineByOffset(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length);
}
return _lineTree.GetByOffset(offset);
}
IDocumentLine IDocument.GetLineByOffset(int offset)
{
return GetLineByOffset(offset);
}
#endregion
#region GetOffset / GetLocation
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(TextLocation location)
{
return GetOffset(location.Line, location.Column);
}
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(int line, int column)
{
var docLine = GetLineByNumber(line);
if (column <= 0)
return docLine.Offset;
if (column > docLine.Length)
return docLine.EndOffset;
return docLine.Offset + column - 1;
}
/// <summary>
/// Gets the location from an offset.
/// </summary>
/// <seealso cref="GetOffset(TextLocation)"/>
public TextLocation GetLocation(int offset)
{
var line = GetLineByOffset(offset);
return new TextLocation(line.LineNumber, offset - line.Offset + 1);
}
#endregion
#region Line Trackers
private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>();
/// <summary>
/// Gets the list of <see cref="ILineTracker"/>s attached to this document.
/// You can add custom line trackers to this list.
/// </summary>
public IList<ILineTracker> LineTrackers
{
get
{
VerifyAccess();
return _lineTrackers;
}
}
#endregion
#region UndoStack
public UndoStack _undoStack;
/// <summary>
/// Gets the <see cref="UndoStack"/> of the document.
/// </summary>
/// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks>
public UndoStack UndoStack
{
get => _undoStack;
set
{
if (value == null)
throw new ArgumentNullException();
if (value != _undoStack)
{
_undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document
// ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress)
_undoStack = value;
OnPropertyChanged("UndoStack");
}
}
}
#endregion
#region CreateAnchor
/// <summary>
/// Creates a new <see cref="TextAnchor"/> at the specified offset.
/// </summary>
/// <inheritdoc cref="TextAnchor" select="remarks|example"/>
public TextAnchor CreateAnchor(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
return _anchorTree.CreateAnchor(offset);
}
ITextAnchor IDocument.CreateAnchor(int offset)
{
return CreateAnchor(offset);
}
#endregion
#region LineCount
/// <summary>
/// Gets the total number of lines in the document.
/// Runtime: O(1).
/// </summary>
public int LineCount
{
get
{
VerifyAccess();
return _lineTree.LineCount;
}
}
/// <summary>
/// Is raised when the LineCount property changes.
/// </summary>
public event EventHandler LineCountChanged;
#endregion
#region Debugging
[Conditional("DEBUG")]
internal void DebugVerifyAccess()
{
VerifyAccess();
}
/// <summary>
/// Gets the document lines tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetLineTreeAsString()
{
#if DEBUG
return _lineTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
/// <summary>
/// Gets the text anchor tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetTextAnchorTreeAsString()
{
#if DEBUG
return _anchorTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
#endregion
#region Service Provider
private IServiceProvider _serviceProvider;
internal IServiceProvider ServiceProvider
{
get
{
VerifyAccess();
if (_serviceProvider == null)
{
var container = new ServiceContainer();
container.AddService(this);
container.AddService<IDocument>(this);
_serviceProvider = container;
}
return _serviceProvider;
}
set
{
VerifyAccess();
_serviceProvider = value ?? throw new ArgumentNullException(nameof(value));
}
}
object IServiceProvider.GetService(Type serviceType)
{
return ServiceProvider.GetService(serviceType);
}
#endregion
#region FileName
private string _fileName;
/// <inheritdoc/>
public event EventHandler FileNameChanged;
private void OnFileNameChanged(EventArgs e)
{
FileNameChanged?.Invoke(this, e);
}
/// <inheritdoc/>
public string FileName
{
get { return _fileName; }
set
{
if (_fileName != value)
{
_fileName = value;
OnFileNameChanged(EventArgs.Empty);
}
}
}
#endregion
}
}
<MSG> Merge pull request #51 from danwalmsley/fix-thread-verification
verify access checks against thread textdocument is created on.
<DFF> @@ -26,6 +26,7 @@ using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
+using System.Threading;
namespace AvaloniaEdit.Document
{
@@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document
return _rope.ToString(offset, length);
}
+ private Thread ownerThread = Thread.CurrentThread;
+
private void VerifyAccess()
{
- Dispatcher.UIThread.VerifyAccess();
+ if(Thread.CurrentThread != ownerThread)
+ {
+ throw new InvalidOperationException("Call from invalid thread.");
+ }
}
/// <summary>
| 7 | Merge pull request #51 from danwalmsley/fix-thread-verification | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059877 | <NME> TextDocument.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
namespace AvaloniaEdit.Document
{
/// <summary>
/// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events.
/// </summary>
/// <remarks>
/// <b>Thread safety:</b>
/// <inheritdoc cref="VerifyAccess"/>
/// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para>
/// </remarks>
public sealed class TextDocument : IDocument, INotifyPropertyChanged
{
#region Thread ownership
private readonly object _lockObject = new object();
#endregion
#region Fields + Constructor
private readonly Rope<char> _rope;
private readonly DocumentLineTree _lineTree;
private readonly LineManager _lineManager;
private readonly TextAnchorTree _anchorTree;
private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider();
/// <summary>
/// Create an empty text document.
/// </summary>
public TextDocument()
: this(string.Empty.ToCharArray())
{
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(IEnumerable<char> initialText)
{
if (initialText == null)
throw new ArgumentNullException(nameof(initialText));
_rope = new Rope<char>(initialText);
_lineTree = new DocumentLineTree(this);
_lineManager = new LineManager(_lineTree, this);
_lineTrackers.CollectionChanged += delegate
{
_lineManager.UpdateListOfLineTrackers();
};
_anchorTree = new TextAnchorTree(this);
_undoStack = new UndoStack();
FireChangeEvents();
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(ITextSource initialText)
: this(GetTextFromTextSource(initialText))
{
}
// gets the text from a text source, directly retrieving the underlying rope where possible
private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource)
{
if (textSource == null)
throw new ArgumentNullException(nameof(textSource));
if (textSource is RopeTextSource rts)
{
return rts.GetRope();
}
if (textSource is TextDocument doc)
{
return doc._rope;
}
return textSource.Text.ToCharArray();
}
#endregion
#region Text
private void ThrowIfRangeInvalid(int offset, int length)
{
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
if (length < 0 || offset + length > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
}
/// <inheritdoc/>
public string GetText(int offset, int length)
{
VerifyAccess();
return _rope.ToString(offset, length);
}
private void VerifyAccess()
{
Dispatcher.UIThread.VerifyAccess();
}
/// <summary>
public void SetOwnerThread(Thread newOwner)
{
// We need to lock here to ensure that in the null owner case,
// only one thread succeeds in taking ownership.
lock (_lockObject) {
if (ownerThread != null) {
VerifyAccess();
}
ownerThread = newOwner;
}
}
private void VerifyAccess()
{
if(Thread.CurrentThread != ownerThread)
{
throw new InvalidOperationException("Call from invalid thread.");
}
}
/// <summary>
/// Retrieves the text for a portion of the document.
/// </summary>
public string GetText(ISegment segment)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
return GetText(segment.Offset, segment.Length);
}
/// <inheritdoc/>
public int IndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.IndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int LastIndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.LastIndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int IndexOfAny(char[] anyOf, int startIndex, int count)
{
DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds
return _rope.IndexOfAny(anyOf, startIndex, count);
}
/// <inheritdoc/>
public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.IndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.LastIndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public char GetCharAt(int offset)
{
DebugVerifyAccess(); // frequently called, so must be fast in release builds
return _rope[offset];
}
private WeakReference _cachedText;
/// <summary>
/// Gets/Sets the text of the whole document.
/// </summary>
public string Text
{
get
{
VerifyAccess();
var completeText = _cachedText?.Target as string;
if (completeText == null)
{
completeText = _rope.ToString();
_cachedText = new WeakReference(completeText);
}
return completeText;
}
set
{
VerifyAccess();
if (value == null)
throw new ArgumentNullException(nameof(value));
Replace(0, _rope.Length, value);
}
}
/// <summary>
/// This event is called after a group of changes is completed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextChanged;
event EventHandler IDocument.ChangeCompleted
{
add => TextChanged += value;
remove => TextChanged -= value;
}
/// <inheritdoc/>
public int TextLength
{
get
{
VerifyAccess();
return _rope.Length;
}
}
/// <summary>
/// Is raised when the TextLength property changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextLengthChanged;
/// <summary>
/// Is raised before the document changes.
/// </summary>
/// <remarks>
/// <para>Here is the order in which events are raised during a document update:</para>
/// <list type="bullet">
/// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description>Start of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateStarted"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="Changing"/> event is raised</description></item>
/// <item><description>The document is changed</description></item>
/// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were
/// in the deleted text portion</description></item>
/// <item><description><see cref="Changed"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="TextChanged"/> event is raised</description></item>
/// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item>
/// <item><description>End of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateFinished"/> event is raised</description></item>
/// </list></item>
/// </list>
/// <para>
/// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>,
/// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>.
/// </para><para>
/// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls.
/// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done.
/// </para><para>
/// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step.
/// </para>
/// </remarks>
public event EventHandler<DocumentChangeEventArgs> Changing;
// Unfortunately EventHandler<T> is invariant, so we have to use two separate events
private event EventHandler<TextChangeEventArgs> TextChangingInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanging
{
add => TextChangingInternal += value;
remove => TextChangingInternal -= value;
}
/// <summary>
/// Is raised after the document has changed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler<DocumentChangeEventArgs> Changed;
private event EventHandler<TextChangeEventArgs> TextChangedInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanged
{
add => TextChangedInternal += value;
remove => TextChangedInternal -= value;
}
/// <summary>
/// Creates a snapshot of the current text.
/// </summary>
/// <remarks>
/// <para>This method returns an immutable snapshot of the document, and may be safely called even when
/// the document's owner thread is concurrently modifying the document.
/// </para><para>
/// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other
/// classes implementing ITextSource.CreateSnapshot().
/// </para><para>
/// </para>
/// </remarks>
public ITextSource CreateSnapshot()
{
lock (_lockObject)
{
return new RopeTextSource(_rope, _versionProvider.CurrentVersion);
}
}
/// <summary>
/// Creates a snapshot of a part of the current text.
/// </summary>
/// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks>
public ITextSource CreateSnapshot(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextSource(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public ITextSourceVersion Version => _versionProvider.CurrentVersion;
/// <inheritdoc/>
public TextReader CreateReader()
{
lock (_lockObject)
{
return new RopeTextReader(_rope);
}
}
/// <inheritdoc/>
public TextReader CreateReader(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextReader(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer)
{
VerifyAccess();
_rope.WriteTo(writer, 0, _rope.Length);
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer, int offset, int length)
{
VerifyAccess();
_rope.WriteTo(writer, offset, length);
}
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region BeginUpdate / EndUpdate
private int _beginUpdateCount;
/// <summary>
/// Gets if an update is running.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public bool IsInUpdate
{
get
{
VerifyAccess();
return _beginUpdateCount > 0;
}
}
/// <summary>
/// Immediately calls <see cref="BeginUpdate()"/>,
/// and returns an IDisposable that calls <see cref="EndUpdate()"/>.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public IDisposable RunUpdate()
{
BeginUpdate();
return new CallbackOnDispose(EndUpdate);
}
/// <summary>
/// <para>Begins a group of document changes.</para>
/// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will
/// group all changes into a single action.</para>
/// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number
/// of EndUpdate calls the events resume their work.</para>
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void BeginUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot change document within another document change.");
_beginUpdateCount++;
if (_beginUpdateCount == 1)
{
_undoStack.StartUndoGroup();
UpdateStarted?.Invoke(this, EventArgs.Empty);
}
}
/// <summary>
/// Ends a group of document changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void EndUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot end update within document change.");
if (_beginUpdateCount == 0)
throw new InvalidOperationException("No update is active.");
if (_beginUpdateCount == 1)
{
// fire change events inside the change group - event handlers might add additional
// document changes to the change group
FireChangeEvents();
_undoStack.EndUndoGroup();
_beginUpdateCount = 0;
UpdateFinished?.Invoke(this, EventArgs.Empty);
}
else
{
_beginUpdateCount -= 1;
}
}
/// <summary>
/// Occurs when a document change starts.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateStarted;
/// <summary>
/// Occurs when a document change is finished.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateFinished;
void IDocument.StartUndoableAction()
{
BeginUpdate();
}
void IDocument.EndUndoableAction()
{
EndUpdate();
}
IDisposable IDocument.OpenUndoGroup()
{
return RunUpdate();
}
#endregion
#region Fire events after update
private int _oldTextLength;
private int _oldLineCount;
private bool _fireTextChanged;
/// <summary>
/// Fires TextChanged, TextLengthChanged, LineCountChanged if required.
/// </summary>
internal void FireChangeEvents()
{
// it may be necessary to fire the event multiple times if the document is changed
// from inside the event handlers
while (_fireTextChanged)
{
_fireTextChanged = false;
TextChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("Text");
var textLength = _rope.Length;
if (textLength != _oldTextLength)
{
_oldTextLength = textLength;
TextLengthChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("TextLength");
}
var lineCount = _lineTree.LineCount;
if (lineCount != _oldLineCount)
{
_oldLineCount = lineCount;
LineCountChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("LineCount");
}
}
}
#endregion
#region Insert / Remove / Replace
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, string text)
{
Replace(offset, 0, new StringTextSource(text), null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, ITextSource text)
{
Replace(offset, 0, text, null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, new StringTextSource(text), null);
}
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, text, null);
}
}
/// <summary>
/// Removes text.
/// </summary>
public void Remove(ISegment segment)
{
Replace(segment, string.Empty);
}
/// <summary>
/// Removes text.
/// </summary>
/// <param name="offset">Starting offset of the text to be removed.</param>
/// <param name="length">Length of the text to be removed.</param>
public void Remove(int offset, int length)
{
Replace(offset, length, StringTextSource.Empty);
}
internal bool InDocumentChanging;
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, string text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, ITextSource text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, string text)
{
Replace(offset, length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, ITextSource text)
{
Replace(offset, length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMappingType);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType)
{
if (text == null)
throw new ArgumentNullException(nameof(text));
// Please see OffsetChangeMappingType XML comments for details on how these modes work.
switch (offsetChangeMappingType)
{
case OffsetChangeMappingType.Normal:
Replace(offset, length, text, null);
break;
case OffsetChangeMappingType.KeepAnchorBeforeInsertion:
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(
new OffsetChangeMapEntry(offset, length, text.TextLength, false, true)));
break;
case OffsetChangeMappingType.RemoveAndInsert:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else
{
var map = new OffsetChangeMap(2)
{
new OffsetChangeMapEntry(offset, length, 0),
new OffsetChangeMapEntry(offset, 0, text.TextLength)
};
map.Freeze();
Replace(offset, length, text, map);
}
break;
case OffsetChangeMappingType.CharacterReplace:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else if (text.TextLength > length)
{
// look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace
// the last character
var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else if (text.TextLength < length)
{
var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else
{
Replace(offset, length, text, OffsetChangeMap.Empty);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value");
}
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMap);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap)
{
text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text));
offsetChangeMap?.Freeze();
// Ensure that all changes take place inside an update group.
// Will also take care of throwing an exception if inDocumentChanging is set.
BeginUpdate();
try
{
// protect document change against corruption by other changes inside the event handlers
InDocumentChanging = true;
try
{
// The range verification must wait until after the BeginUpdate() call because the document
// might be modified inside the UpdateStarted event.
ThrowIfRangeInvalid(offset, length);
DoReplace(offset, length, text, offsetChangeMap);
}
finally
{
InDocumentChanging = false;
}
}
finally
{
EndUpdate();
}
}
private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap)
{
if (length == 0 && newText.TextLength == 0)
return;
// trying to replace a single character in 'Normal' mode?
// for single characters, 'CharacterReplace' mode is equivalent, but more performant
// (we don't have to touch the anchorTree at all in 'CharacterReplace' mode)
if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null)
offsetChangeMap = OffsetChangeMap.Empty;
ITextSource removedText;
if (length == 0)
{
removedText = StringTextSource.Empty;
}
else if (length < 100)
{
removedText = new StringTextSource(_rope.ToString(offset, length));
}
else
{
// use a rope if the removed string is long
removedText = new RopeTextSource(_rope.GetRange(offset, length));
}
var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap);
// fire DocumentChanging event
Changing?.Invoke(this, args);
TextChangingInternal?.Invoke(this, args);
_undoStack.Push(this, args);
_cachedText = null; // reset cache of complete document text
_fireTextChanged = true;
var delayedEvents = new DelayedEvents();
lock (_lockObject)
{
// create linked list of checkpoints
_versionProvider.AppendChange(args);
// now update the textBuffer and lineTree
if (offset == 0 && length == _rope.Length)
{
// optimize replacing the whole document
_rope.Clear();
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(0, newRopeTextSource.GetRope());
else
_rope.InsertText(0, newText.Text);
_lineManager.Rebuild();
}
else
{
_rope.RemoveRange(offset, length);
_lineManager.Remove(offset, length);
#if DEBUG
_lineTree.CheckProperties();
#endif
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(offset, newRopeTextSource.GetRope());
else
_rope.InsertText(offset, newText.Text);
_lineManager.Insert(offset, newText);
#if DEBUG
_lineTree.CheckProperties();
#endif
}
}
// update text anchors
if (offsetChangeMap == null)
{
_anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents);
}
else
{
foreach (var entry in offsetChangeMap)
{
_anchorTree.HandleTextChange(entry, delayedEvents);
}
}
_lineManager.ChangeComplete(args);
// raise delayed events after our data structures are consistent again
delayedEvents.RaiseEvents();
// fire DocumentChanged event
Changed?.Invoke(this, args);
TextChangedInternal?.Invoke(this, args);
}
#endregion
#region GetLineBy...
/// <summary>
/// Gets a read-only list of lines.
/// </summary>
/// <remarks><inheritdoc cref="DocumentLine"/></remarks>
public IList<DocumentLine> Lines => _lineTree;
/// <summary>
/// Gets a line by the line number: O(log n)
/// </summary>
public DocumentLine GetLineByNumber(int number)
{
VerifyAccess();
if (number < 1 || number > _lineTree.LineCount)
throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount);
return _lineTree.GetByNumber(number);
}
IDocumentLine IDocument.GetLineByNumber(int lineNumber)
{
return GetLineByNumber(lineNumber);
}
/// <summary>
/// Gets a document lines by offset.
/// Runtime: O(log n)
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")]
public DocumentLine GetLineByOffset(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length);
}
return _lineTree.GetByOffset(offset);
}
IDocumentLine IDocument.GetLineByOffset(int offset)
{
return GetLineByOffset(offset);
}
#endregion
#region GetOffset / GetLocation
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(TextLocation location)
{
return GetOffset(location.Line, location.Column);
}
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(int line, int column)
{
var docLine = GetLineByNumber(line);
if (column <= 0)
return docLine.Offset;
if (column > docLine.Length)
return docLine.EndOffset;
return docLine.Offset + column - 1;
}
/// <summary>
/// Gets the location from an offset.
/// </summary>
/// <seealso cref="GetOffset(TextLocation)"/>
public TextLocation GetLocation(int offset)
{
var line = GetLineByOffset(offset);
return new TextLocation(line.LineNumber, offset - line.Offset + 1);
}
#endregion
#region Line Trackers
private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>();
/// <summary>
/// Gets the list of <see cref="ILineTracker"/>s attached to this document.
/// You can add custom line trackers to this list.
/// </summary>
public IList<ILineTracker> LineTrackers
{
get
{
VerifyAccess();
return _lineTrackers;
}
}
#endregion
#region UndoStack
public UndoStack _undoStack;
/// <summary>
/// Gets the <see cref="UndoStack"/> of the document.
/// </summary>
/// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks>
public UndoStack UndoStack
{
get => _undoStack;
set
{
if (value == null)
throw new ArgumentNullException();
if (value != _undoStack)
{
_undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document
// ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress)
_undoStack = value;
OnPropertyChanged("UndoStack");
}
}
}
#endregion
#region CreateAnchor
/// <summary>
/// Creates a new <see cref="TextAnchor"/> at the specified offset.
/// </summary>
/// <inheritdoc cref="TextAnchor" select="remarks|example"/>
public TextAnchor CreateAnchor(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
return _anchorTree.CreateAnchor(offset);
}
ITextAnchor IDocument.CreateAnchor(int offset)
{
return CreateAnchor(offset);
}
#endregion
#region LineCount
/// <summary>
/// Gets the total number of lines in the document.
/// Runtime: O(1).
/// </summary>
public int LineCount
{
get
{
VerifyAccess();
return _lineTree.LineCount;
}
}
/// <summary>
/// Is raised when the LineCount property changes.
/// </summary>
public event EventHandler LineCountChanged;
#endregion
#region Debugging
[Conditional("DEBUG")]
internal void DebugVerifyAccess()
{
VerifyAccess();
}
/// <summary>
/// Gets the document lines tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetLineTreeAsString()
{
#if DEBUG
return _lineTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
/// <summary>
/// Gets the text anchor tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetTextAnchorTreeAsString()
{
#if DEBUG
return _anchorTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
#endregion
#region Service Provider
private IServiceProvider _serviceProvider;
internal IServiceProvider ServiceProvider
{
get
{
VerifyAccess();
if (_serviceProvider == null)
{
var container = new ServiceContainer();
container.AddService(this);
container.AddService<IDocument>(this);
_serviceProvider = container;
}
return _serviceProvider;
}
set
{
VerifyAccess();
_serviceProvider = value ?? throw new ArgumentNullException(nameof(value));
}
}
object IServiceProvider.GetService(Type serviceType)
{
return ServiceProvider.GetService(serviceType);
}
#endregion
#region FileName
private string _fileName;
/// <inheritdoc/>
public event EventHandler FileNameChanged;
private void OnFileNameChanged(EventArgs e)
{
FileNameChanged?.Invoke(this, e);
}
/// <inheritdoc/>
public string FileName
{
get { return _fileName; }
set
{
if (_fileName != value)
{
_fileName = value;
OnFileNameChanged(EventArgs.Empty);
}
}
}
#endregion
}
}
<MSG> Merge pull request #51 from danwalmsley/fix-thread-verification
verify access checks against thread textdocument is created on.
<DFF> @@ -26,6 +26,7 @@ using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
+using System.Threading;
namespace AvaloniaEdit.Document
{
@@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document
return _rope.ToString(offset, length);
}
+ private Thread ownerThread = Thread.CurrentThread;
+
private void VerifyAccess()
{
- Dispatcher.UIThread.VerifyAccess();
+ if(Thread.CurrentThread != ownerThread)
+ {
+ throw new InvalidOperationException("Call from invalid thread.");
+ }
}
/// <summary>
| 7 | Merge pull request #51 from danwalmsley/fix-thread-verification | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059878 | <NME> TextDocument.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
namespace AvaloniaEdit.Document
{
/// <summary>
/// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events.
/// </summary>
/// <remarks>
/// <b>Thread safety:</b>
/// <inheritdoc cref="VerifyAccess"/>
/// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para>
/// </remarks>
public sealed class TextDocument : IDocument, INotifyPropertyChanged
{
#region Thread ownership
private readonly object _lockObject = new object();
#endregion
#region Fields + Constructor
private readonly Rope<char> _rope;
private readonly DocumentLineTree _lineTree;
private readonly LineManager _lineManager;
private readonly TextAnchorTree _anchorTree;
private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider();
/// <summary>
/// Create an empty text document.
/// </summary>
public TextDocument()
: this(string.Empty.ToCharArray())
{
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(IEnumerable<char> initialText)
{
if (initialText == null)
throw new ArgumentNullException(nameof(initialText));
_rope = new Rope<char>(initialText);
_lineTree = new DocumentLineTree(this);
_lineManager = new LineManager(_lineTree, this);
_lineTrackers.CollectionChanged += delegate
{
_lineManager.UpdateListOfLineTrackers();
};
_anchorTree = new TextAnchorTree(this);
_undoStack = new UndoStack();
FireChangeEvents();
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(ITextSource initialText)
: this(GetTextFromTextSource(initialText))
{
}
// gets the text from a text source, directly retrieving the underlying rope where possible
private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource)
{
if (textSource == null)
throw new ArgumentNullException(nameof(textSource));
if (textSource is RopeTextSource rts)
{
return rts.GetRope();
}
if (textSource is TextDocument doc)
{
return doc._rope;
}
return textSource.Text.ToCharArray();
}
#endregion
#region Text
private void ThrowIfRangeInvalid(int offset, int length)
{
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
if (length < 0 || offset + length > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
}
/// <inheritdoc/>
public string GetText(int offset, int length)
{
VerifyAccess();
return _rope.ToString(offset, length);
}
private void VerifyAccess()
{
Dispatcher.UIThread.VerifyAccess();
}
/// <summary>
public void SetOwnerThread(Thread newOwner)
{
// We need to lock here to ensure that in the null owner case,
// only one thread succeeds in taking ownership.
lock (_lockObject) {
if (ownerThread != null) {
VerifyAccess();
}
ownerThread = newOwner;
}
}
private void VerifyAccess()
{
if(Thread.CurrentThread != ownerThread)
{
throw new InvalidOperationException("Call from invalid thread.");
}
}
/// <summary>
/// Retrieves the text for a portion of the document.
/// </summary>
public string GetText(ISegment segment)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
return GetText(segment.Offset, segment.Length);
}
/// <inheritdoc/>
public int IndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.IndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int LastIndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.LastIndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int IndexOfAny(char[] anyOf, int startIndex, int count)
{
DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds
return _rope.IndexOfAny(anyOf, startIndex, count);
}
/// <inheritdoc/>
public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.IndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.LastIndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public char GetCharAt(int offset)
{
DebugVerifyAccess(); // frequently called, so must be fast in release builds
return _rope[offset];
}
private WeakReference _cachedText;
/// <summary>
/// Gets/Sets the text of the whole document.
/// </summary>
public string Text
{
get
{
VerifyAccess();
var completeText = _cachedText?.Target as string;
if (completeText == null)
{
completeText = _rope.ToString();
_cachedText = new WeakReference(completeText);
}
return completeText;
}
set
{
VerifyAccess();
if (value == null)
throw new ArgumentNullException(nameof(value));
Replace(0, _rope.Length, value);
}
}
/// <summary>
/// This event is called after a group of changes is completed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextChanged;
event EventHandler IDocument.ChangeCompleted
{
add => TextChanged += value;
remove => TextChanged -= value;
}
/// <inheritdoc/>
public int TextLength
{
get
{
VerifyAccess();
return _rope.Length;
}
}
/// <summary>
/// Is raised when the TextLength property changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextLengthChanged;
/// <summary>
/// Is raised before the document changes.
/// </summary>
/// <remarks>
/// <para>Here is the order in which events are raised during a document update:</para>
/// <list type="bullet">
/// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description>Start of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateStarted"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="Changing"/> event is raised</description></item>
/// <item><description>The document is changed</description></item>
/// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were
/// in the deleted text portion</description></item>
/// <item><description><see cref="Changed"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="TextChanged"/> event is raised</description></item>
/// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item>
/// <item><description>End of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateFinished"/> event is raised</description></item>
/// </list></item>
/// </list>
/// <para>
/// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>,
/// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>.
/// </para><para>
/// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls.
/// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done.
/// </para><para>
/// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step.
/// </para>
/// </remarks>
public event EventHandler<DocumentChangeEventArgs> Changing;
// Unfortunately EventHandler<T> is invariant, so we have to use two separate events
private event EventHandler<TextChangeEventArgs> TextChangingInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanging
{
add => TextChangingInternal += value;
remove => TextChangingInternal -= value;
}
/// <summary>
/// Is raised after the document has changed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler<DocumentChangeEventArgs> Changed;
private event EventHandler<TextChangeEventArgs> TextChangedInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanged
{
add => TextChangedInternal += value;
remove => TextChangedInternal -= value;
}
/// <summary>
/// Creates a snapshot of the current text.
/// </summary>
/// <remarks>
/// <para>This method returns an immutable snapshot of the document, and may be safely called even when
/// the document's owner thread is concurrently modifying the document.
/// </para><para>
/// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other
/// classes implementing ITextSource.CreateSnapshot().
/// </para><para>
/// </para>
/// </remarks>
public ITextSource CreateSnapshot()
{
lock (_lockObject)
{
return new RopeTextSource(_rope, _versionProvider.CurrentVersion);
}
}
/// <summary>
/// Creates a snapshot of a part of the current text.
/// </summary>
/// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks>
public ITextSource CreateSnapshot(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextSource(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public ITextSourceVersion Version => _versionProvider.CurrentVersion;
/// <inheritdoc/>
public TextReader CreateReader()
{
lock (_lockObject)
{
return new RopeTextReader(_rope);
}
}
/// <inheritdoc/>
public TextReader CreateReader(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextReader(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer)
{
VerifyAccess();
_rope.WriteTo(writer, 0, _rope.Length);
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer, int offset, int length)
{
VerifyAccess();
_rope.WriteTo(writer, offset, length);
}
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region BeginUpdate / EndUpdate
private int _beginUpdateCount;
/// <summary>
/// Gets if an update is running.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public bool IsInUpdate
{
get
{
VerifyAccess();
return _beginUpdateCount > 0;
}
}
/// <summary>
/// Immediately calls <see cref="BeginUpdate()"/>,
/// and returns an IDisposable that calls <see cref="EndUpdate()"/>.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public IDisposable RunUpdate()
{
BeginUpdate();
return new CallbackOnDispose(EndUpdate);
}
/// <summary>
/// <para>Begins a group of document changes.</para>
/// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will
/// group all changes into a single action.</para>
/// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number
/// of EndUpdate calls the events resume their work.</para>
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void BeginUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot change document within another document change.");
_beginUpdateCount++;
if (_beginUpdateCount == 1)
{
_undoStack.StartUndoGroup();
UpdateStarted?.Invoke(this, EventArgs.Empty);
}
}
/// <summary>
/// Ends a group of document changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void EndUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot end update within document change.");
if (_beginUpdateCount == 0)
throw new InvalidOperationException("No update is active.");
if (_beginUpdateCount == 1)
{
// fire change events inside the change group - event handlers might add additional
// document changes to the change group
FireChangeEvents();
_undoStack.EndUndoGroup();
_beginUpdateCount = 0;
UpdateFinished?.Invoke(this, EventArgs.Empty);
}
else
{
_beginUpdateCount -= 1;
}
}
/// <summary>
/// Occurs when a document change starts.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateStarted;
/// <summary>
/// Occurs when a document change is finished.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateFinished;
void IDocument.StartUndoableAction()
{
BeginUpdate();
}
void IDocument.EndUndoableAction()
{
EndUpdate();
}
IDisposable IDocument.OpenUndoGroup()
{
return RunUpdate();
}
#endregion
#region Fire events after update
private int _oldTextLength;
private int _oldLineCount;
private bool _fireTextChanged;
/// <summary>
/// Fires TextChanged, TextLengthChanged, LineCountChanged if required.
/// </summary>
internal void FireChangeEvents()
{
// it may be necessary to fire the event multiple times if the document is changed
// from inside the event handlers
while (_fireTextChanged)
{
_fireTextChanged = false;
TextChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("Text");
var textLength = _rope.Length;
if (textLength != _oldTextLength)
{
_oldTextLength = textLength;
TextLengthChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("TextLength");
}
var lineCount = _lineTree.LineCount;
if (lineCount != _oldLineCount)
{
_oldLineCount = lineCount;
LineCountChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("LineCount");
}
}
}
#endregion
#region Insert / Remove / Replace
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, string text)
{
Replace(offset, 0, new StringTextSource(text), null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, ITextSource text)
{
Replace(offset, 0, text, null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, new StringTextSource(text), null);
}
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, text, null);
}
}
/// <summary>
/// Removes text.
/// </summary>
public void Remove(ISegment segment)
{
Replace(segment, string.Empty);
}
/// <summary>
/// Removes text.
/// </summary>
/// <param name="offset">Starting offset of the text to be removed.</param>
/// <param name="length">Length of the text to be removed.</param>
public void Remove(int offset, int length)
{
Replace(offset, length, StringTextSource.Empty);
}
internal bool InDocumentChanging;
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, string text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, ITextSource text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, string text)
{
Replace(offset, length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, ITextSource text)
{
Replace(offset, length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMappingType);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType)
{
if (text == null)
throw new ArgumentNullException(nameof(text));
// Please see OffsetChangeMappingType XML comments for details on how these modes work.
switch (offsetChangeMappingType)
{
case OffsetChangeMappingType.Normal:
Replace(offset, length, text, null);
break;
case OffsetChangeMappingType.KeepAnchorBeforeInsertion:
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(
new OffsetChangeMapEntry(offset, length, text.TextLength, false, true)));
break;
case OffsetChangeMappingType.RemoveAndInsert:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else
{
var map = new OffsetChangeMap(2)
{
new OffsetChangeMapEntry(offset, length, 0),
new OffsetChangeMapEntry(offset, 0, text.TextLength)
};
map.Freeze();
Replace(offset, length, text, map);
}
break;
case OffsetChangeMappingType.CharacterReplace:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else if (text.TextLength > length)
{
// look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace
// the last character
var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else if (text.TextLength < length)
{
var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else
{
Replace(offset, length, text, OffsetChangeMap.Empty);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value");
}
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMap);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap)
{
text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text));
offsetChangeMap?.Freeze();
// Ensure that all changes take place inside an update group.
// Will also take care of throwing an exception if inDocumentChanging is set.
BeginUpdate();
try
{
// protect document change against corruption by other changes inside the event handlers
InDocumentChanging = true;
try
{
// The range verification must wait until after the BeginUpdate() call because the document
// might be modified inside the UpdateStarted event.
ThrowIfRangeInvalid(offset, length);
DoReplace(offset, length, text, offsetChangeMap);
}
finally
{
InDocumentChanging = false;
}
}
finally
{
EndUpdate();
}
}
private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap)
{
if (length == 0 && newText.TextLength == 0)
return;
// trying to replace a single character in 'Normal' mode?
// for single characters, 'CharacterReplace' mode is equivalent, but more performant
// (we don't have to touch the anchorTree at all in 'CharacterReplace' mode)
if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null)
offsetChangeMap = OffsetChangeMap.Empty;
ITextSource removedText;
if (length == 0)
{
removedText = StringTextSource.Empty;
}
else if (length < 100)
{
removedText = new StringTextSource(_rope.ToString(offset, length));
}
else
{
// use a rope if the removed string is long
removedText = new RopeTextSource(_rope.GetRange(offset, length));
}
var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap);
// fire DocumentChanging event
Changing?.Invoke(this, args);
TextChangingInternal?.Invoke(this, args);
_undoStack.Push(this, args);
_cachedText = null; // reset cache of complete document text
_fireTextChanged = true;
var delayedEvents = new DelayedEvents();
lock (_lockObject)
{
// create linked list of checkpoints
_versionProvider.AppendChange(args);
// now update the textBuffer and lineTree
if (offset == 0 && length == _rope.Length)
{
// optimize replacing the whole document
_rope.Clear();
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(0, newRopeTextSource.GetRope());
else
_rope.InsertText(0, newText.Text);
_lineManager.Rebuild();
}
else
{
_rope.RemoveRange(offset, length);
_lineManager.Remove(offset, length);
#if DEBUG
_lineTree.CheckProperties();
#endif
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(offset, newRopeTextSource.GetRope());
else
_rope.InsertText(offset, newText.Text);
_lineManager.Insert(offset, newText);
#if DEBUG
_lineTree.CheckProperties();
#endif
}
}
// update text anchors
if (offsetChangeMap == null)
{
_anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents);
}
else
{
foreach (var entry in offsetChangeMap)
{
_anchorTree.HandleTextChange(entry, delayedEvents);
}
}
_lineManager.ChangeComplete(args);
// raise delayed events after our data structures are consistent again
delayedEvents.RaiseEvents();
// fire DocumentChanged event
Changed?.Invoke(this, args);
TextChangedInternal?.Invoke(this, args);
}
#endregion
#region GetLineBy...
/// <summary>
/// Gets a read-only list of lines.
/// </summary>
/// <remarks><inheritdoc cref="DocumentLine"/></remarks>
public IList<DocumentLine> Lines => _lineTree;
/// <summary>
/// Gets a line by the line number: O(log n)
/// </summary>
public DocumentLine GetLineByNumber(int number)
{
VerifyAccess();
if (number < 1 || number > _lineTree.LineCount)
throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount);
return _lineTree.GetByNumber(number);
}
IDocumentLine IDocument.GetLineByNumber(int lineNumber)
{
return GetLineByNumber(lineNumber);
}
/// <summary>
/// Gets a document lines by offset.
/// Runtime: O(log n)
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")]
public DocumentLine GetLineByOffset(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length);
}
return _lineTree.GetByOffset(offset);
}
IDocumentLine IDocument.GetLineByOffset(int offset)
{
return GetLineByOffset(offset);
}
#endregion
#region GetOffset / GetLocation
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(TextLocation location)
{
return GetOffset(location.Line, location.Column);
}
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(int line, int column)
{
var docLine = GetLineByNumber(line);
if (column <= 0)
return docLine.Offset;
if (column > docLine.Length)
return docLine.EndOffset;
return docLine.Offset + column - 1;
}
/// <summary>
/// Gets the location from an offset.
/// </summary>
/// <seealso cref="GetOffset(TextLocation)"/>
public TextLocation GetLocation(int offset)
{
var line = GetLineByOffset(offset);
return new TextLocation(line.LineNumber, offset - line.Offset + 1);
}
#endregion
#region Line Trackers
private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>();
/// <summary>
/// Gets the list of <see cref="ILineTracker"/>s attached to this document.
/// You can add custom line trackers to this list.
/// </summary>
public IList<ILineTracker> LineTrackers
{
get
{
VerifyAccess();
return _lineTrackers;
}
}
#endregion
#region UndoStack
public UndoStack _undoStack;
/// <summary>
/// Gets the <see cref="UndoStack"/> of the document.
/// </summary>
/// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks>
public UndoStack UndoStack
{
get => _undoStack;
set
{
if (value == null)
throw new ArgumentNullException();
if (value != _undoStack)
{
_undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document
// ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress)
_undoStack = value;
OnPropertyChanged("UndoStack");
}
}
}
#endregion
#region CreateAnchor
/// <summary>
/// Creates a new <see cref="TextAnchor"/> at the specified offset.
/// </summary>
/// <inheritdoc cref="TextAnchor" select="remarks|example"/>
public TextAnchor CreateAnchor(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
return _anchorTree.CreateAnchor(offset);
}
ITextAnchor IDocument.CreateAnchor(int offset)
{
return CreateAnchor(offset);
}
#endregion
#region LineCount
/// <summary>
/// Gets the total number of lines in the document.
/// Runtime: O(1).
/// </summary>
public int LineCount
{
get
{
VerifyAccess();
return _lineTree.LineCount;
}
}
/// <summary>
/// Is raised when the LineCount property changes.
/// </summary>
public event EventHandler LineCountChanged;
#endregion
#region Debugging
[Conditional("DEBUG")]
internal void DebugVerifyAccess()
{
VerifyAccess();
}
/// <summary>
/// Gets the document lines tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetLineTreeAsString()
{
#if DEBUG
return _lineTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
/// <summary>
/// Gets the text anchor tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetTextAnchorTreeAsString()
{
#if DEBUG
return _anchorTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
#endregion
#region Service Provider
private IServiceProvider _serviceProvider;
internal IServiceProvider ServiceProvider
{
get
{
VerifyAccess();
if (_serviceProvider == null)
{
var container = new ServiceContainer();
container.AddService(this);
container.AddService<IDocument>(this);
_serviceProvider = container;
}
return _serviceProvider;
}
set
{
VerifyAccess();
_serviceProvider = value ?? throw new ArgumentNullException(nameof(value));
}
}
object IServiceProvider.GetService(Type serviceType)
{
return ServiceProvider.GetService(serviceType);
}
#endregion
#region FileName
private string _fileName;
/// <inheritdoc/>
public event EventHandler FileNameChanged;
private void OnFileNameChanged(EventArgs e)
{
FileNameChanged?.Invoke(this, e);
}
/// <inheritdoc/>
public string FileName
{
get { return _fileName; }
set
{
if (_fileName != value)
{
_fileName = value;
OnFileNameChanged(EventArgs.Empty);
}
}
}
#endregion
}
}
<MSG> Merge pull request #51 from danwalmsley/fix-thread-verification
verify access checks against thread textdocument is created on.
<DFF> @@ -26,6 +26,7 @@ using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
+using System.Threading;
namespace AvaloniaEdit.Document
{
@@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document
return _rope.ToString(offset, length);
}
+ private Thread ownerThread = Thread.CurrentThread;
+
private void VerifyAccess()
{
- Dispatcher.UIThread.VerifyAccess();
+ if(Thread.CurrentThread != ownerThread)
+ {
+ throw new InvalidOperationException("Call from invalid thread.");
+ }
}
/// <summary>
| 7 | Merge pull request #51 from danwalmsley/fix-thread-verification | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059879 | <NME> TextDocument.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
namespace AvaloniaEdit.Document
{
/// <summary>
/// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events.
/// </summary>
/// <remarks>
/// <b>Thread safety:</b>
/// <inheritdoc cref="VerifyAccess"/>
/// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para>
/// </remarks>
public sealed class TextDocument : IDocument, INotifyPropertyChanged
{
#region Thread ownership
private readonly object _lockObject = new object();
#endregion
#region Fields + Constructor
private readonly Rope<char> _rope;
private readonly DocumentLineTree _lineTree;
private readonly LineManager _lineManager;
private readonly TextAnchorTree _anchorTree;
private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider();
/// <summary>
/// Create an empty text document.
/// </summary>
public TextDocument()
: this(string.Empty.ToCharArray())
{
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(IEnumerable<char> initialText)
{
if (initialText == null)
throw new ArgumentNullException(nameof(initialText));
_rope = new Rope<char>(initialText);
_lineTree = new DocumentLineTree(this);
_lineManager = new LineManager(_lineTree, this);
_lineTrackers.CollectionChanged += delegate
{
_lineManager.UpdateListOfLineTrackers();
};
_anchorTree = new TextAnchorTree(this);
_undoStack = new UndoStack();
FireChangeEvents();
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(ITextSource initialText)
: this(GetTextFromTextSource(initialText))
{
}
// gets the text from a text source, directly retrieving the underlying rope where possible
private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource)
{
if (textSource == null)
throw new ArgumentNullException(nameof(textSource));
if (textSource is RopeTextSource rts)
{
return rts.GetRope();
}
if (textSource is TextDocument doc)
{
return doc._rope;
}
return textSource.Text.ToCharArray();
}
#endregion
#region Text
private void ThrowIfRangeInvalid(int offset, int length)
{
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
if (length < 0 || offset + length > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
}
/// <inheritdoc/>
public string GetText(int offset, int length)
{
VerifyAccess();
return _rope.ToString(offset, length);
}
private void VerifyAccess()
{
Dispatcher.UIThread.VerifyAccess();
}
/// <summary>
public void SetOwnerThread(Thread newOwner)
{
// We need to lock here to ensure that in the null owner case,
// only one thread succeeds in taking ownership.
lock (_lockObject) {
if (ownerThread != null) {
VerifyAccess();
}
ownerThread = newOwner;
}
}
private void VerifyAccess()
{
if(Thread.CurrentThread != ownerThread)
{
throw new InvalidOperationException("Call from invalid thread.");
}
}
/// <summary>
/// Retrieves the text for a portion of the document.
/// </summary>
public string GetText(ISegment segment)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
return GetText(segment.Offset, segment.Length);
}
/// <inheritdoc/>
public int IndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.IndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int LastIndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.LastIndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int IndexOfAny(char[] anyOf, int startIndex, int count)
{
DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds
return _rope.IndexOfAny(anyOf, startIndex, count);
}
/// <inheritdoc/>
public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.IndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.LastIndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public char GetCharAt(int offset)
{
DebugVerifyAccess(); // frequently called, so must be fast in release builds
return _rope[offset];
}
private WeakReference _cachedText;
/// <summary>
/// Gets/Sets the text of the whole document.
/// </summary>
public string Text
{
get
{
VerifyAccess();
var completeText = _cachedText?.Target as string;
if (completeText == null)
{
completeText = _rope.ToString();
_cachedText = new WeakReference(completeText);
}
return completeText;
}
set
{
VerifyAccess();
if (value == null)
throw new ArgumentNullException(nameof(value));
Replace(0, _rope.Length, value);
}
}
/// <summary>
/// This event is called after a group of changes is completed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextChanged;
event EventHandler IDocument.ChangeCompleted
{
add => TextChanged += value;
remove => TextChanged -= value;
}
/// <inheritdoc/>
public int TextLength
{
get
{
VerifyAccess();
return _rope.Length;
}
}
/// <summary>
/// Is raised when the TextLength property changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextLengthChanged;
/// <summary>
/// Is raised before the document changes.
/// </summary>
/// <remarks>
/// <para>Here is the order in which events are raised during a document update:</para>
/// <list type="bullet">
/// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description>Start of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateStarted"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="Changing"/> event is raised</description></item>
/// <item><description>The document is changed</description></item>
/// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were
/// in the deleted text portion</description></item>
/// <item><description><see cref="Changed"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="TextChanged"/> event is raised</description></item>
/// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item>
/// <item><description>End of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateFinished"/> event is raised</description></item>
/// </list></item>
/// </list>
/// <para>
/// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>,
/// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>.
/// </para><para>
/// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls.
/// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done.
/// </para><para>
/// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step.
/// </para>
/// </remarks>
public event EventHandler<DocumentChangeEventArgs> Changing;
// Unfortunately EventHandler<T> is invariant, so we have to use two separate events
private event EventHandler<TextChangeEventArgs> TextChangingInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanging
{
add => TextChangingInternal += value;
remove => TextChangingInternal -= value;
}
/// <summary>
/// Is raised after the document has changed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler<DocumentChangeEventArgs> Changed;
private event EventHandler<TextChangeEventArgs> TextChangedInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanged
{
add => TextChangedInternal += value;
remove => TextChangedInternal -= value;
}
/// <summary>
/// Creates a snapshot of the current text.
/// </summary>
/// <remarks>
/// <para>This method returns an immutable snapshot of the document, and may be safely called even when
/// the document's owner thread is concurrently modifying the document.
/// </para><para>
/// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other
/// classes implementing ITextSource.CreateSnapshot().
/// </para><para>
/// </para>
/// </remarks>
public ITextSource CreateSnapshot()
{
lock (_lockObject)
{
return new RopeTextSource(_rope, _versionProvider.CurrentVersion);
}
}
/// <summary>
/// Creates a snapshot of a part of the current text.
/// </summary>
/// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks>
public ITextSource CreateSnapshot(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextSource(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public ITextSourceVersion Version => _versionProvider.CurrentVersion;
/// <inheritdoc/>
public TextReader CreateReader()
{
lock (_lockObject)
{
return new RopeTextReader(_rope);
}
}
/// <inheritdoc/>
public TextReader CreateReader(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextReader(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer)
{
VerifyAccess();
_rope.WriteTo(writer, 0, _rope.Length);
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer, int offset, int length)
{
VerifyAccess();
_rope.WriteTo(writer, offset, length);
}
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region BeginUpdate / EndUpdate
private int _beginUpdateCount;
/// <summary>
/// Gets if an update is running.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public bool IsInUpdate
{
get
{
VerifyAccess();
return _beginUpdateCount > 0;
}
}
/// <summary>
/// Immediately calls <see cref="BeginUpdate()"/>,
/// and returns an IDisposable that calls <see cref="EndUpdate()"/>.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public IDisposable RunUpdate()
{
BeginUpdate();
return new CallbackOnDispose(EndUpdate);
}
/// <summary>
/// <para>Begins a group of document changes.</para>
/// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will
/// group all changes into a single action.</para>
/// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number
/// of EndUpdate calls the events resume their work.</para>
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void BeginUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot change document within another document change.");
_beginUpdateCount++;
if (_beginUpdateCount == 1)
{
_undoStack.StartUndoGroup();
UpdateStarted?.Invoke(this, EventArgs.Empty);
}
}
/// <summary>
/// Ends a group of document changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void EndUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot end update within document change.");
if (_beginUpdateCount == 0)
throw new InvalidOperationException("No update is active.");
if (_beginUpdateCount == 1)
{
// fire change events inside the change group - event handlers might add additional
// document changes to the change group
FireChangeEvents();
_undoStack.EndUndoGroup();
_beginUpdateCount = 0;
UpdateFinished?.Invoke(this, EventArgs.Empty);
}
else
{
_beginUpdateCount -= 1;
}
}
/// <summary>
/// Occurs when a document change starts.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateStarted;
/// <summary>
/// Occurs when a document change is finished.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateFinished;
void IDocument.StartUndoableAction()
{
BeginUpdate();
}
void IDocument.EndUndoableAction()
{
EndUpdate();
}
IDisposable IDocument.OpenUndoGroup()
{
return RunUpdate();
}
#endregion
#region Fire events after update
private int _oldTextLength;
private int _oldLineCount;
private bool _fireTextChanged;
/// <summary>
/// Fires TextChanged, TextLengthChanged, LineCountChanged if required.
/// </summary>
internal void FireChangeEvents()
{
// it may be necessary to fire the event multiple times if the document is changed
// from inside the event handlers
while (_fireTextChanged)
{
_fireTextChanged = false;
TextChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("Text");
var textLength = _rope.Length;
if (textLength != _oldTextLength)
{
_oldTextLength = textLength;
TextLengthChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("TextLength");
}
var lineCount = _lineTree.LineCount;
if (lineCount != _oldLineCount)
{
_oldLineCount = lineCount;
LineCountChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("LineCount");
}
}
}
#endregion
#region Insert / Remove / Replace
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, string text)
{
Replace(offset, 0, new StringTextSource(text), null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, ITextSource text)
{
Replace(offset, 0, text, null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, new StringTextSource(text), null);
}
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, text, null);
}
}
/// <summary>
/// Removes text.
/// </summary>
public void Remove(ISegment segment)
{
Replace(segment, string.Empty);
}
/// <summary>
/// Removes text.
/// </summary>
/// <param name="offset">Starting offset of the text to be removed.</param>
/// <param name="length">Length of the text to be removed.</param>
public void Remove(int offset, int length)
{
Replace(offset, length, StringTextSource.Empty);
}
internal bool InDocumentChanging;
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, string text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, ITextSource text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, string text)
{
Replace(offset, length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, ITextSource text)
{
Replace(offset, length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMappingType);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType)
{
if (text == null)
throw new ArgumentNullException(nameof(text));
// Please see OffsetChangeMappingType XML comments for details on how these modes work.
switch (offsetChangeMappingType)
{
case OffsetChangeMappingType.Normal:
Replace(offset, length, text, null);
break;
case OffsetChangeMappingType.KeepAnchorBeforeInsertion:
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(
new OffsetChangeMapEntry(offset, length, text.TextLength, false, true)));
break;
case OffsetChangeMappingType.RemoveAndInsert:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else
{
var map = new OffsetChangeMap(2)
{
new OffsetChangeMapEntry(offset, length, 0),
new OffsetChangeMapEntry(offset, 0, text.TextLength)
};
map.Freeze();
Replace(offset, length, text, map);
}
break;
case OffsetChangeMappingType.CharacterReplace:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else if (text.TextLength > length)
{
// look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace
// the last character
var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else if (text.TextLength < length)
{
var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else
{
Replace(offset, length, text, OffsetChangeMap.Empty);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value");
}
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMap);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap)
{
text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text));
offsetChangeMap?.Freeze();
// Ensure that all changes take place inside an update group.
// Will also take care of throwing an exception if inDocumentChanging is set.
BeginUpdate();
try
{
// protect document change against corruption by other changes inside the event handlers
InDocumentChanging = true;
try
{
// The range verification must wait until after the BeginUpdate() call because the document
// might be modified inside the UpdateStarted event.
ThrowIfRangeInvalid(offset, length);
DoReplace(offset, length, text, offsetChangeMap);
}
finally
{
InDocumentChanging = false;
}
}
finally
{
EndUpdate();
}
}
private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap)
{
if (length == 0 && newText.TextLength == 0)
return;
// trying to replace a single character in 'Normal' mode?
// for single characters, 'CharacterReplace' mode is equivalent, but more performant
// (we don't have to touch the anchorTree at all in 'CharacterReplace' mode)
if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null)
offsetChangeMap = OffsetChangeMap.Empty;
ITextSource removedText;
if (length == 0)
{
removedText = StringTextSource.Empty;
}
else if (length < 100)
{
removedText = new StringTextSource(_rope.ToString(offset, length));
}
else
{
// use a rope if the removed string is long
removedText = new RopeTextSource(_rope.GetRange(offset, length));
}
var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap);
// fire DocumentChanging event
Changing?.Invoke(this, args);
TextChangingInternal?.Invoke(this, args);
_undoStack.Push(this, args);
_cachedText = null; // reset cache of complete document text
_fireTextChanged = true;
var delayedEvents = new DelayedEvents();
lock (_lockObject)
{
// create linked list of checkpoints
_versionProvider.AppendChange(args);
// now update the textBuffer and lineTree
if (offset == 0 && length == _rope.Length)
{
// optimize replacing the whole document
_rope.Clear();
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(0, newRopeTextSource.GetRope());
else
_rope.InsertText(0, newText.Text);
_lineManager.Rebuild();
}
else
{
_rope.RemoveRange(offset, length);
_lineManager.Remove(offset, length);
#if DEBUG
_lineTree.CheckProperties();
#endif
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(offset, newRopeTextSource.GetRope());
else
_rope.InsertText(offset, newText.Text);
_lineManager.Insert(offset, newText);
#if DEBUG
_lineTree.CheckProperties();
#endif
}
}
// update text anchors
if (offsetChangeMap == null)
{
_anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents);
}
else
{
foreach (var entry in offsetChangeMap)
{
_anchorTree.HandleTextChange(entry, delayedEvents);
}
}
_lineManager.ChangeComplete(args);
// raise delayed events after our data structures are consistent again
delayedEvents.RaiseEvents();
// fire DocumentChanged event
Changed?.Invoke(this, args);
TextChangedInternal?.Invoke(this, args);
}
#endregion
#region GetLineBy...
/// <summary>
/// Gets a read-only list of lines.
/// </summary>
/// <remarks><inheritdoc cref="DocumentLine"/></remarks>
public IList<DocumentLine> Lines => _lineTree;
/// <summary>
/// Gets a line by the line number: O(log n)
/// </summary>
public DocumentLine GetLineByNumber(int number)
{
VerifyAccess();
if (number < 1 || number > _lineTree.LineCount)
throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount);
return _lineTree.GetByNumber(number);
}
IDocumentLine IDocument.GetLineByNumber(int lineNumber)
{
return GetLineByNumber(lineNumber);
}
/// <summary>
/// Gets a document lines by offset.
/// Runtime: O(log n)
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")]
public DocumentLine GetLineByOffset(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length);
}
return _lineTree.GetByOffset(offset);
}
IDocumentLine IDocument.GetLineByOffset(int offset)
{
return GetLineByOffset(offset);
}
#endregion
#region GetOffset / GetLocation
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(TextLocation location)
{
return GetOffset(location.Line, location.Column);
}
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(int line, int column)
{
var docLine = GetLineByNumber(line);
if (column <= 0)
return docLine.Offset;
if (column > docLine.Length)
return docLine.EndOffset;
return docLine.Offset + column - 1;
}
/// <summary>
/// Gets the location from an offset.
/// </summary>
/// <seealso cref="GetOffset(TextLocation)"/>
public TextLocation GetLocation(int offset)
{
var line = GetLineByOffset(offset);
return new TextLocation(line.LineNumber, offset - line.Offset + 1);
}
#endregion
#region Line Trackers
private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>();
/// <summary>
/// Gets the list of <see cref="ILineTracker"/>s attached to this document.
/// You can add custom line trackers to this list.
/// </summary>
public IList<ILineTracker> LineTrackers
{
get
{
VerifyAccess();
return _lineTrackers;
}
}
#endregion
#region UndoStack
public UndoStack _undoStack;
/// <summary>
/// Gets the <see cref="UndoStack"/> of the document.
/// </summary>
/// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks>
public UndoStack UndoStack
{
get => _undoStack;
set
{
if (value == null)
throw new ArgumentNullException();
if (value != _undoStack)
{
_undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document
// ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress)
_undoStack = value;
OnPropertyChanged("UndoStack");
}
}
}
#endregion
#region CreateAnchor
/// <summary>
/// Creates a new <see cref="TextAnchor"/> at the specified offset.
/// </summary>
/// <inheritdoc cref="TextAnchor" select="remarks|example"/>
public TextAnchor CreateAnchor(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
return _anchorTree.CreateAnchor(offset);
}
ITextAnchor IDocument.CreateAnchor(int offset)
{
return CreateAnchor(offset);
}
#endregion
#region LineCount
/// <summary>
/// Gets the total number of lines in the document.
/// Runtime: O(1).
/// </summary>
public int LineCount
{
get
{
VerifyAccess();
return _lineTree.LineCount;
}
}
/// <summary>
/// Is raised when the LineCount property changes.
/// </summary>
public event EventHandler LineCountChanged;
#endregion
#region Debugging
[Conditional("DEBUG")]
internal void DebugVerifyAccess()
{
VerifyAccess();
}
/// <summary>
/// Gets the document lines tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetLineTreeAsString()
{
#if DEBUG
return _lineTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
/// <summary>
/// Gets the text anchor tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetTextAnchorTreeAsString()
{
#if DEBUG
return _anchorTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
#endregion
#region Service Provider
private IServiceProvider _serviceProvider;
internal IServiceProvider ServiceProvider
{
get
{
VerifyAccess();
if (_serviceProvider == null)
{
var container = new ServiceContainer();
container.AddService(this);
container.AddService<IDocument>(this);
_serviceProvider = container;
}
return _serviceProvider;
}
set
{
VerifyAccess();
_serviceProvider = value ?? throw new ArgumentNullException(nameof(value));
}
}
object IServiceProvider.GetService(Type serviceType)
{
return ServiceProvider.GetService(serviceType);
}
#endregion
#region FileName
private string _fileName;
/// <inheritdoc/>
public event EventHandler FileNameChanged;
private void OnFileNameChanged(EventArgs e)
{
FileNameChanged?.Invoke(this, e);
}
/// <inheritdoc/>
public string FileName
{
get { return _fileName; }
set
{
if (_fileName != value)
{
_fileName = value;
OnFileNameChanged(EventArgs.Empty);
}
}
}
#endregion
}
}
<MSG> Merge pull request #51 from danwalmsley/fix-thread-verification
verify access checks against thread textdocument is created on.
<DFF> @@ -26,6 +26,7 @@ using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
+using System.Threading;
namespace AvaloniaEdit.Document
{
@@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document
return _rope.ToString(offset, length);
}
+ private Thread ownerThread = Thread.CurrentThread;
+
private void VerifyAccess()
{
- Dispatcher.UIThread.VerifyAccess();
+ if(Thread.CurrentThread != ownerThread)
+ {
+ throw new InvalidOperationException("Call from invalid thread.");
+ }
}
/// <summary>
| 7 | Merge pull request #51 from danwalmsley/fix-thread-verification | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059880 | <NME> TextDocument.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
namespace AvaloniaEdit.Document
{
/// <summary>
/// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events.
/// </summary>
/// <remarks>
/// <b>Thread safety:</b>
/// <inheritdoc cref="VerifyAccess"/>
/// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para>
/// </remarks>
public sealed class TextDocument : IDocument, INotifyPropertyChanged
{
#region Thread ownership
private readonly object _lockObject = new object();
#endregion
#region Fields + Constructor
private readonly Rope<char> _rope;
private readonly DocumentLineTree _lineTree;
private readonly LineManager _lineManager;
private readonly TextAnchorTree _anchorTree;
private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider();
/// <summary>
/// Create an empty text document.
/// </summary>
public TextDocument()
: this(string.Empty.ToCharArray())
{
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(IEnumerable<char> initialText)
{
if (initialText == null)
throw new ArgumentNullException(nameof(initialText));
_rope = new Rope<char>(initialText);
_lineTree = new DocumentLineTree(this);
_lineManager = new LineManager(_lineTree, this);
_lineTrackers.CollectionChanged += delegate
{
_lineManager.UpdateListOfLineTrackers();
};
_anchorTree = new TextAnchorTree(this);
_undoStack = new UndoStack();
FireChangeEvents();
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(ITextSource initialText)
: this(GetTextFromTextSource(initialText))
{
}
// gets the text from a text source, directly retrieving the underlying rope where possible
private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource)
{
if (textSource == null)
throw new ArgumentNullException(nameof(textSource));
if (textSource is RopeTextSource rts)
{
return rts.GetRope();
}
if (textSource is TextDocument doc)
{
return doc._rope;
}
return textSource.Text.ToCharArray();
}
#endregion
#region Text
private void ThrowIfRangeInvalid(int offset, int length)
{
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
if (length < 0 || offset + length > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
}
/// <inheritdoc/>
public string GetText(int offset, int length)
{
VerifyAccess();
return _rope.ToString(offset, length);
}
private void VerifyAccess()
{
Dispatcher.UIThread.VerifyAccess();
}
/// <summary>
public void SetOwnerThread(Thread newOwner)
{
// We need to lock here to ensure that in the null owner case,
// only one thread succeeds in taking ownership.
lock (_lockObject) {
if (ownerThread != null) {
VerifyAccess();
}
ownerThread = newOwner;
}
}
private void VerifyAccess()
{
if(Thread.CurrentThread != ownerThread)
{
throw new InvalidOperationException("Call from invalid thread.");
}
}
/// <summary>
/// Retrieves the text for a portion of the document.
/// </summary>
public string GetText(ISegment segment)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
return GetText(segment.Offset, segment.Length);
}
/// <inheritdoc/>
public int IndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.IndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int LastIndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.LastIndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int IndexOfAny(char[] anyOf, int startIndex, int count)
{
DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds
return _rope.IndexOfAny(anyOf, startIndex, count);
}
/// <inheritdoc/>
public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.IndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.LastIndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public char GetCharAt(int offset)
{
DebugVerifyAccess(); // frequently called, so must be fast in release builds
return _rope[offset];
}
private WeakReference _cachedText;
/// <summary>
/// Gets/Sets the text of the whole document.
/// </summary>
public string Text
{
get
{
VerifyAccess();
var completeText = _cachedText?.Target as string;
if (completeText == null)
{
completeText = _rope.ToString();
_cachedText = new WeakReference(completeText);
}
return completeText;
}
set
{
VerifyAccess();
if (value == null)
throw new ArgumentNullException(nameof(value));
Replace(0, _rope.Length, value);
}
}
/// <summary>
/// This event is called after a group of changes is completed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextChanged;
event EventHandler IDocument.ChangeCompleted
{
add => TextChanged += value;
remove => TextChanged -= value;
}
/// <inheritdoc/>
public int TextLength
{
get
{
VerifyAccess();
return _rope.Length;
}
}
/// <summary>
/// Is raised when the TextLength property changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextLengthChanged;
/// <summary>
/// Is raised before the document changes.
/// </summary>
/// <remarks>
/// <para>Here is the order in which events are raised during a document update:</para>
/// <list type="bullet">
/// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description>Start of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateStarted"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="Changing"/> event is raised</description></item>
/// <item><description>The document is changed</description></item>
/// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were
/// in the deleted text portion</description></item>
/// <item><description><see cref="Changed"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="TextChanged"/> event is raised</description></item>
/// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item>
/// <item><description>End of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateFinished"/> event is raised</description></item>
/// </list></item>
/// </list>
/// <para>
/// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>,
/// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>.
/// </para><para>
/// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls.
/// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done.
/// </para><para>
/// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step.
/// </para>
/// </remarks>
public event EventHandler<DocumentChangeEventArgs> Changing;
// Unfortunately EventHandler<T> is invariant, so we have to use two separate events
private event EventHandler<TextChangeEventArgs> TextChangingInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanging
{
add => TextChangingInternal += value;
remove => TextChangingInternal -= value;
}
/// <summary>
/// Is raised after the document has changed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler<DocumentChangeEventArgs> Changed;
private event EventHandler<TextChangeEventArgs> TextChangedInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanged
{
add => TextChangedInternal += value;
remove => TextChangedInternal -= value;
}
/// <summary>
/// Creates a snapshot of the current text.
/// </summary>
/// <remarks>
/// <para>This method returns an immutable snapshot of the document, and may be safely called even when
/// the document's owner thread is concurrently modifying the document.
/// </para><para>
/// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other
/// classes implementing ITextSource.CreateSnapshot().
/// </para><para>
/// </para>
/// </remarks>
public ITextSource CreateSnapshot()
{
lock (_lockObject)
{
return new RopeTextSource(_rope, _versionProvider.CurrentVersion);
}
}
/// <summary>
/// Creates a snapshot of a part of the current text.
/// </summary>
/// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks>
public ITextSource CreateSnapshot(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextSource(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public ITextSourceVersion Version => _versionProvider.CurrentVersion;
/// <inheritdoc/>
public TextReader CreateReader()
{
lock (_lockObject)
{
return new RopeTextReader(_rope);
}
}
/// <inheritdoc/>
public TextReader CreateReader(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextReader(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer)
{
VerifyAccess();
_rope.WriteTo(writer, 0, _rope.Length);
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer, int offset, int length)
{
VerifyAccess();
_rope.WriteTo(writer, offset, length);
}
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region BeginUpdate / EndUpdate
private int _beginUpdateCount;
/// <summary>
/// Gets if an update is running.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public bool IsInUpdate
{
get
{
VerifyAccess();
return _beginUpdateCount > 0;
}
}
/// <summary>
/// Immediately calls <see cref="BeginUpdate()"/>,
/// and returns an IDisposable that calls <see cref="EndUpdate()"/>.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public IDisposable RunUpdate()
{
BeginUpdate();
return new CallbackOnDispose(EndUpdate);
}
/// <summary>
/// <para>Begins a group of document changes.</para>
/// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will
/// group all changes into a single action.</para>
/// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number
/// of EndUpdate calls the events resume their work.</para>
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void BeginUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot change document within another document change.");
_beginUpdateCount++;
if (_beginUpdateCount == 1)
{
_undoStack.StartUndoGroup();
UpdateStarted?.Invoke(this, EventArgs.Empty);
}
}
/// <summary>
/// Ends a group of document changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void EndUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot end update within document change.");
if (_beginUpdateCount == 0)
throw new InvalidOperationException("No update is active.");
if (_beginUpdateCount == 1)
{
// fire change events inside the change group - event handlers might add additional
// document changes to the change group
FireChangeEvents();
_undoStack.EndUndoGroup();
_beginUpdateCount = 0;
UpdateFinished?.Invoke(this, EventArgs.Empty);
}
else
{
_beginUpdateCount -= 1;
}
}
/// <summary>
/// Occurs when a document change starts.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateStarted;
/// <summary>
/// Occurs when a document change is finished.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateFinished;
void IDocument.StartUndoableAction()
{
BeginUpdate();
}
void IDocument.EndUndoableAction()
{
EndUpdate();
}
IDisposable IDocument.OpenUndoGroup()
{
return RunUpdate();
}
#endregion
#region Fire events after update
private int _oldTextLength;
private int _oldLineCount;
private bool _fireTextChanged;
/// <summary>
/// Fires TextChanged, TextLengthChanged, LineCountChanged if required.
/// </summary>
internal void FireChangeEvents()
{
// it may be necessary to fire the event multiple times if the document is changed
// from inside the event handlers
while (_fireTextChanged)
{
_fireTextChanged = false;
TextChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("Text");
var textLength = _rope.Length;
if (textLength != _oldTextLength)
{
_oldTextLength = textLength;
TextLengthChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("TextLength");
}
var lineCount = _lineTree.LineCount;
if (lineCount != _oldLineCount)
{
_oldLineCount = lineCount;
LineCountChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("LineCount");
}
}
}
#endregion
#region Insert / Remove / Replace
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, string text)
{
Replace(offset, 0, new StringTextSource(text), null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, ITextSource text)
{
Replace(offset, 0, text, null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, new StringTextSource(text), null);
}
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, text, null);
}
}
/// <summary>
/// Removes text.
/// </summary>
public void Remove(ISegment segment)
{
Replace(segment, string.Empty);
}
/// <summary>
/// Removes text.
/// </summary>
/// <param name="offset">Starting offset of the text to be removed.</param>
/// <param name="length">Length of the text to be removed.</param>
public void Remove(int offset, int length)
{
Replace(offset, length, StringTextSource.Empty);
}
internal bool InDocumentChanging;
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, string text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, ITextSource text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, string text)
{
Replace(offset, length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, ITextSource text)
{
Replace(offset, length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMappingType);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType)
{
if (text == null)
throw new ArgumentNullException(nameof(text));
// Please see OffsetChangeMappingType XML comments for details on how these modes work.
switch (offsetChangeMappingType)
{
case OffsetChangeMappingType.Normal:
Replace(offset, length, text, null);
break;
case OffsetChangeMappingType.KeepAnchorBeforeInsertion:
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(
new OffsetChangeMapEntry(offset, length, text.TextLength, false, true)));
break;
case OffsetChangeMappingType.RemoveAndInsert:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else
{
var map = new OffsetChangeMap(2)
{
new OffsetChangeMapEntry(offset, length, 0),
new OffsetChangeMapEntry(offset, 0, text.TextLength)
};
map.Freeze();
Replace(offset, length, text, map);
}
break;
case OffsetChangeMappingType.CharacterReplace:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else if (text.TextLength > length)
{
// look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace
// the last character
var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else if (text.TextLength < length)
{
var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else
{
Replace(offset, length, text, OffsetChangeMap.Empty);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value");
}
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMap);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap)
{
text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text));
offsetChangeMap?.Freeze();
// Ensure that all changes take place inside an update group.
// Will also take care of throwing an exception if inDocumentChanging is set.
BeginUpdate();
try
{
// protect document change against corruption by other changes inside the event handlers
InDocumentChanging = true;
try
{
// The range verification must wait until after the BeginUpdate() call because the document
// might be modified inside the UpdateStarted event.
ThrowIfRangeInvalid(offset, length);
DoReplace(offset, length, text, offsetChangeMap);
}
finally
{
InDocumentChanging = false;
}
}
finally
{
EndUpdate();
}
}
private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap)
{
if (length == 0 && newText.TextLength == 0)
return;
// trying to replace a single character in 'Normal' mode?
// for single characters, 'CharacterReplace' mode is equivalent, but more performant
// (we don't have to touch the anchorTree at all in 'CharacterReplace' mode)
if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null)
offsetChangeMap = OffsetChangeMap.Empty;
ITextSource removedText;
if (length == 0)
{
removedText = StringTextSource.Empty;
}
else if (length < 100)
{
removedText = new StringTextSource(_rope.ToString(offset, length));
}
else
{
// use a rope if the removed string is long
removedText = new RopeTextSource(_rope.GetRange(offset, length));
}
var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap);
// fire DocumentChanging event
Changing?.Invoke(this, args);
TextChangingInternal?.Invoke(this, args);
_undoStack.Push(this, args);
_cachedText = null; // reset cache of complete document text
_fireTextChanged = true;
var delayedEvents = new DelayedEvents();
lock (_lockObject)
{
// create linked list of checkpoints
_versionProvider.AppendChange(args);
// now update the textBuffer and lineTree
if (offset == 0 && length == _rope.Length)
{
// optimize replacing the whole document
_rope.Clear();
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(0, newRopeTextSource.GetRope());
else
_rope.InsertText(0, newText.Text);
_lineManager.Rebuild();
}
else
{
_rope.RemoveRange(offset, length);
_lineManager.Remove(offset, length);
#if DEBUG
_lineTree.CheckProperties();
#endif
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(offset, newRopeTextSource.GetRope());
else
_rope.InsertText(offset, newText.Text);
_lineManager.Insert(offset, newText);
#if DEBUG
_lineTree.CheckProperties();
#endif
}
}
// update text anchors
if (offsetChangeMap == null)
{
_anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents);
}
else
{
foreach (var entry in offsetChangeMap)
{
_anchorTree.HandleTextChange(entry, delayedEvents);
}
}
_lineManager.ChangeComplete(args);
// raise delayed events after our data structures are consistent again
delayedEvents.RaiseEvents();
// fire DocumentChanged event
Changed?.Invoke(this, args);
TextChangedInternal?.Invoke(this, args);
}
#endregion
#region GetLineBy...
/// <summary>
/// Gets a read-only list of lines.
/// </summary>
/// <remarks><inheritdoc cref="DocumentLine"/></remarks>
public IList<DocumentLine> Lines => _lineTree;
/// <summary>
/// Gets a line by the line number: O(log n)
/// </summary>
public DocumentLine GetLineByNumber(int number)
{
VerifyAccess();
if (number < 1 || number > _lineTree.LineCount)
throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount);
return _lineTree.GetByNumber(number);
}
IDocumentLine IDocument.GetLineByNumber(int lineNumber)
{
return GetLineByNumber(lineNumber);
}
/// <summary>
/// Gets a document lines by offset.
/// Runtime: O(log n)
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")]
public DocumentLine GetLineByOffset(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length);
}
return _lineTree.GetByOffset(offset);
}
IDocumentLine IDocument.GetLineByOffset(int offset)
{
return GetLineByOffset(offset);
}
#endregion
#region GetOffset / GetLocation
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(TextLocation location)
{
return GetOffset(location.Line, location.Column);
}
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(int line, int column)
{
var docLine = GetLineByNumber(line);
if (column <= 0)
return docLine.Offset;
if (column > docLine.Length)
return docLine.EndOffset;
return docLine.Offset + column - 1;
}
/// <summary>
/// Gets the location from an offset.
/// </summary>
/// <seealso cref="GetOffset(TextLocation)"/>
public TextLocation GetLocation(int offset)
{
var line = GetLineByOffset(offset);
return new TextLocation(line.LineNumber, offset - line.Offset + 1);
}
#endregion
#region Line Trackers
private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>();
/// <summary>
/// Gets the list of <see cref="ILineTracker"/>s attached to this document.
/// You can add custom line trackers to this list.
/// </summary>
public IList<ILineTracker> LineTrackers
{
get
{
VerifyAccess();
return _lineTrackers;
}
}
#endregion
#region UndoStack
public UndoStack _undoStack;
/// <summary>
/// Gets the <see cref="UndoStack"/> of the document.
/// </summary>
/// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks>
public UndoStack UndoStack
{
get => _undoStack;
set
{
if (value == null)
throw new ArgumentNullException();
if (value != _undoStack)
{
_undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document
// ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress)
_undoStack = value;
OnPropertyChanged("UndoStack");
}
}
}
#endregion
#region CreateAnchor
/// <summary>
/// Creates a new <see cref="TextAnchor"/> at the specified offset.
/// </summary>
/// <inheritdoc cref="TextAnchor" select="remarks|example"/>
public TextAnchor CreateAnchor(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
return _anchorTree.CreateAnchor(offset);
}
ITextAnchor IDocument.CreateAnchor(int offset)
{
return CreateAnchor(offset);
}
#endregion
#region LineCount
/// <summary>
/// Gets the total number of lines in the document.
/// Runtime: O(1).
/// </summary>
public int LineCount
{
get
{
VerifyAccess();
return _lineTree.LineCount;
}
}
/// <summary>
/// Is raised when the LineCount property changes.
/// </summary>
public event EventHandler LineCountChanged;
#endregion
#region Debugging
[Conditional("DEBUG")]
internal void DebugVerifyAccess()
{
VerifyAccess();
}
/// <summary>
/// Gets the document lines tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetLineTreeAsString()
{
#if DEBUG
return _lineTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
/// <summary>
/// Gets the text anchor tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetTextAnchorTreeAsString()
{
#if DEBUG
return _anchorTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
#endregion
#region Service Provider
private IServiceProvider _serviceProvider;
internal IServiceProvider ServiceProvider
{
get
{
VerifyAccess();
if (_serviceProvider == null)
{
var container = new ServiceContainer();
container.AddService(this);
container.AddService<IDocument>(this);
_serviceProvider = container;
}
return _serviceProvider;
}
set
{
VerifyAccess();
_serviceProvider = value ?? throw new ArgumentNullException(nameof(value));
}
}
object IServiceProvider.GetService(Type serviceType)
{
return ServiceProvider.GetService(serviceType);
}
#endregion
#region FileName
private string _fileName;
/// <inheritdoc/>
public event EventHandler FileNameChanged;
private void OnFileNameChanged(EventArgs e)
{
FileNameChanged?.Invoke(this, e);
}
/// <inheritdoc/>
public string FileName
{
get { return _fileName; }
set
{
if (_fileName != value)
{
_fileName = value;
OnFileNameChanged(EventArgs.Empty);
}
}
}
#endregion
}
}
<MSG> Merge pull request #51 from danwalmsley/fix-thread-verification
verify access checks against thread textdocument is created on.
<DFF> @@ -26,6 +26,7 @@ using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
+using System.Threading;
namespace AvaloniaEdit.Document
{
@@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document
return _rope.ToString(offset, length);
}
+ private Thread ownerThread = Thread.CurrentThread;
+
private void VerifyAccess()
{
- Dispatcher.UIThread.VerifyAccess();
+ if(Thread.CurrentThread != ownerThread)
+ {
+ throw new InvalidOperationException("Call from invalid thread.");
+ }
}
/// <summary>
| 7 | Merge pull request #51 from danwalmsley/fix-thread-verification | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059881 | <NME> TextDocument.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
namespace AvaloniaEdit.Document
{
/// <summary>
/// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events.
/// </summary>
/// <remarks>
/// <b>Thread safety:</b>
/// <inheritdoc cref="VerifyAccess"/>
/// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para>
/// </remarks>
public sealed class TextDocument : IDocument, INotifyPropertyChanged
{
#region Thread ownership
private readonly object _lockObject = new object();
#endregion
#region Fields + Constructor
private readonly Rope<char> _rope;
private readonly DocumentLineTree _lineTree;
private readonly LineManager _lineManager;
private readonly TextAnchorTree _anchorTree;
private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider();
/// <summary>
/// Create an empty text document.
/// </summary>
public TextDocument()
: this(string.Empty.ToCharArray())
{
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(IEnumerable<char> initialText)
{
if (initialText == null)
throw new ArgumentNullException(nameof(initialText));
_rope = new Rope<char>(initialText);
_lineTree = new DocumentLineTree(this);
_lineManager = new LineManager(_lineTree, this);
_lineTrackers.CollectionChanged += delegate
{
_lineManager.UpdateListOfLineTrackers();
};
_anchorTree = new TextAnchorTree(this);
_undoStack = new UndoStack();
FireChangeEvents();
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(ITextSource initialText)
: this(GetTextFromTextSource(initialText))
{
}
// gets the text from a text source, directly retrieving the underlying rope where possible
private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource)
{
if (textSource == null)
throw new ArgumentNullException(nameof(textSource));
if (textSource is RopeTextSource rts)
{
return rts.GetRope();
}
if (textSource is TextDocument doc)
{
return doc._rope;
}
return textSource.Text.ToCharArray();
}
#endregion
#region Text
private void ThrowIfRangeInvalid(int offset, int length)
{
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
if (length < 0 || offset + length > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
}
/// <inheritdoc/>
public string GetText(int offset, int length)
{
VerifyAccess();
return _rope.ToString(offset, length);
}
private void VerifyAccess()
{
Dispatcher.UIThread.VerifyAccess();
}
/// <summary>
public void SetOwnerThread(Thread newOwner)
{
// We need to lock here to ensure that in the null owner case,
// only one thread succeeds in taking ownership.
lock (_lockObject) {
if (ownerThread != null) {
VerifyAccess();
}
ownerThread = newOwner;
}
}
private void VerifyAccess()
{
if(Thread.CurrentThread != ownerThread)
{
throw new InvalidOperationException("Call from invalid thread.");
}
}
/// <summary>
/// Retrieves the text for a portion of the document.
/// </summary>
public string GetText(ISegment segment)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
return GetText(segment.Offset, segment.Length);
}
/// <inheritdoc/>
public int IndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.IndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int LastIndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.LastIndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int IndexOfAny(char[] anyOf, int startIndex, int count)
{
DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds
return _rope.IndexOfAny(anyOf, startIndex, count);
}
/// <inheritdoc/>
public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.IndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.LastIndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public char GetCharAt(int offset)
{
DebugVerifyAccess(); // frequently called, so must be fast in release builds
return _rope[offset];
}
private WeakReference _cachedText;
/// <summary>
/// Gets/Sets the text of the whole document.
/// </summary>
public string Text
{
get
{
VerifyAccess();
var completeText = _cachedText?.Target as string;
if (completeText == null)
{
completeText = _rope.ToString();
_cachedText = new WeakReference(completeText);
}
return completeText;
}
set
{
VerifyAccess();
if (value == null)
throw new ArgumentNullException(nameof(value));
Replace(0, _rope.Length, value);
}
}
/// <summary>
/// This event is called after a group of changes is completed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextChanged;
event EventHandler IDocument.ChangeCompleted
{
add => TextChanged += value;
remove => TextChanged -= value;
}
/// <inheritdoc/>
public int TextLength
{
get
{
VerifyAccess();
return _rope.Length;
}
}
/// <summary>
/// Is raised when the TextLength property changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextLengthChanged;
/// <summary>
/// Is raised before the document changes.
/// </summary>
/// <remarks>
/// <para>Here is the order in which events are raised during a document update:</para>
/// <list type="bullet">
/// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description>Start of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateStarted"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="Changing"/> event is raised</description></item>
/// <item><description>The document is changed</description></item>
/// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were
/// in the deleted text portion</description></item>
/// <item><description><see cref="Changed"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="TextChanged"/> event is raised</description></item>
/// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item>
/// <item><description>End of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateFinished"/> event is raised</description></item>
/// </list></item>
/// </list>
/// <para>
/// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>,
/// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>.
/// </para><para>
/// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls.
/// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done.
/// </para><para>
/// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step.
/// </para>
/// </remarks>
public event EventHandler<DocumentChangeEventArgs> Changing;
// Unfortunately EventHandler<T> is invariant, so we have to use two separate events
private event EventHandler<TextChangeEventArgs> TextChangingInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanging
{
add => TextChangingInternal += value;
remove => TextChangingInternal -= value;
}
/// <summary>
/// Is raised after the document has changed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler<DocumentChangeEventArgs> Changed;
private event EventHandler<TextChangeEventArgs> TextChangedInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanged
{
add => TextChangedInternal += value;
remove => TextChangedInternal -= value;
}
/// <summary>
/// Creates a snapshot of the current text.
/// </summary>
/// <remarks>
/// <para>This method returns an immutable snapshot of the document, and may be safely called even when
/// the document's owner thread is concurrently modifying the document.
/// </para><para>
/// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other
/// classes implementing ITextSource.CreateSnapshot().
/// </para><para>
/// </para>
/// </remarks>
public ITextSource CreateSnapshot()
{
lock (_lockObject)
{
return new RopeTextSource(_rope, _versionProvider.CurrentVersion);
}
}
/// <summary>
/// Creates a snapshot of a part of the current text.
/// </summary>
/// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks>
public ITextSource CreateSnapshot(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextSource(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public ITextSourceVersion Version => _versionProvider.CurrentVersion;
/// <inheritdoc/>
public TextReader CreateReader()
{
lock (_lockObject)
{
return new RopeTextReader(_rope);
}
}
/// <inheritdoc/>
public TextReader CreateReader(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextReader(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer)
{
VerifyAccess();
_rope.WriteTo(writer, 0, _rope.Length);
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer, int offset, int length)
{
VerifyAccess();
_rope.WriteTo(writer, offset, length);
}
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region BeginUpdate / EndUpdate
private int _beginUpdateCount;
/// <summary>
/// Gets if an update is running.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public bool IsInUpdate
{
get
{
VerifyAccess();
return _beginUpdateCount > 0;
}
}
/// <summary>
/// Immediately calls <see cref="BeginUpdate()"/>,
/// and returns an IDisposable that calls <see cref="EndUpdate()"/>.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public IDisposable RunUpdate()
{
BeginUpdate();
return new CallbackOnDispose(EndUpdate);
}
/// <summary>
/// <para>Begins a group of document changes.</para>
/// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will
/// group all changes into a single action.</para>
/// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number
/// of EndUpdate calls the events resume their work.</para>
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void BeginUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot change document within another document change.");
_beginUpdateCount++;
if (_beginUpdateCount == 1)
{
_undoStack.StartUndoGroup();
UpdateStarted?.Invoke(this, EventArgs.Empty);
}
}
/// <summary>
/// Ends a group of document changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void EndUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot end update within document change.");
if (_beginUpdateCount == 0)
throw new InvalidOperationException("No update is active.");
if (_beginUpdateCount == 1)
{
// fire change events inside the change group - event handlers might add additional
// document changes to the change group
FireChangeEvents();
_undoStack.EndUndoGroup();
_beginUpdateCount = 0;
UpdateFinished?.Invoke(this, EventArgs.Empty);
}
else
{
_beginUpdateCount -= 1;
}
}
/// <summary>
/// Occurs when a document change starts.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateStarted;
/// <summary>
/// Occurs when a document change is finished.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateFinished;
void IDocument.StartUndoableAction()
{
BeginUpdate();
}
void IDocument.EndUndoableAction()
{
EndUpdate();
}
IDisposable IDocument.OpenUndoGroup()
{
return RunUpdate();
}
#endregion
#region Fire events after update
private int _oldTextLength;
private int _oldLineCount;
private bool _fireTextChanged;
/// <summary>
/// Fires TextChanged, TextLengthChanged, LineCountChanged if required.
/// </summary>
internal void FireChangeEvents()
{
// it may be necessary to fire the event multiple times if the document is changed
// from inside the event handlers
while (_fireTextChanged)
{
_fireTextChanged = false;
TextChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("Text");
var textLength = _rope.Length;
if (textLength != _oldTextLength)
{
_oldTextLength = textLength;
TextLengthChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("TextLength");
}
var lineCount = _lineTree.LineCount;
if (lineCount != _oldLineCount)
{
_oldLineCount = lineCount;
LineCountChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("LineCount");
}
}
}
#endregion
#region Insert / Remove / Replace
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, string text)
{
Replace(offset, 0, new StringTextSource(text), null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, ITextSource text)
{
Replace(offset, 0, text, null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, new StringTextSource(text), null);
}
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, text, null);
}
}
/// <summary>
/// Removes text.
/// </summary>
public void Remove(ISegment segment)
{
Replace(segment, string.Empty);
}
/// <summary>
/// Removes text.
/// </summary>
/// <param name="offset">Starting offset of the text to be removed.</param>
/// <param name="length">Length of the text to be removed.</param>
public void Remove(int offset, int length)
{
Replace(offset, length, StringTextSource.Empty);
}
internal bool InDocumentChanging;
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, string text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, ITextSource text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, string text)
{
Replace(offset, length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, ITextSource text)
{
Replace(offset, length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMappingType);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType)
{
if (text == null)
throw new ArgumentNullException(nameof(text));
// Please see OffsetChangeMappingType XML comments for details on how these modes work.
switch (offsetChangeMappingType)
{
case OffsetChangeMappingType.Normal:
Replace(offset, length, text, null);
break;
case OffsetChangeMappingType.KeepAnchorBeforeInsertion:
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(
new OffsetChangeMapEntry(offset, length, text.TextLength, false, true)));
break;
case OffsetChangeMappingType.RemoveAndInsert:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else
{
var map = new OffsetChangeMap(2)
{
new OffsetChangeMapEntry(offset, length, 0),
new OffsetChangeMapEntry(offset, 0, text.TextLength)
};
map.Freeze();
Replace(offset, length, text, map);
}
break;
case OffsetChangeMappingType.CharacterReplace:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else if (text.TextLength > length)
{
// look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace
// the last character
var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else if (text.TextLength < length)
{
var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else
{
Replace(offset, length, text, OffsetChangeMap.Empty);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value");
}
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMap);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap)
{
text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text));
offsetChangeMap?.Freeze();
// Ensure that all changes take place inside an update group.
// Will also take care of throwing an exception if inDocumentChanging is set.
BeginUpdate();
try
{
// protect document change against corruption by other changes inside the event handlers
InDocumentChanging = true;
try
{
// The range verification must wait until after the BeginUpdate() call because the document
// might be modified inside the UpdateStarted event.
ThrowIfRangeInvalid(offset, length);
DoReplace(offset, length, text, offsetChangeMap);
}
finally
{
InDocumentChanging = false;
}
}
finally
{
EndUpdate();
}
}
private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap)
{
if (length == 0 && newText.TextLength == 0)
return;
// trying to replace a single character in 'Normal' mode?
// for single characters, 'CharacterReplace' mode is equivalent, but more performant
// (we don't have to touch the anchorTree at all in 'CharacterReplace' mode)
if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null)
offsetChangeMap = OffsetChangeMap.Empty;
ITextSource removedText;
if (length == 0)
{
removedText = StringTextSource.Empty;
}
else if (length < 100)
{
removedText = new StringTextSource(_rope.ToString(offset, length));
}
else
{
// use a rope if the removed string is long
removedText = new RopeTextSource(_rope.GetRange(offset, length));
}
var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap);
// fire DocumentChanging event
Changing?.Invoke(this, args);
TextChangingInternal?.Invoke(this, args);
_undoStack.Push(this, args);
_cachedText = null; // reset cache of complete document text
_fireTextChanged = true;
var delayedEvents = new DelayedEvents();
lock (_lockObject)
{
// create linked list of checkpoints
_versionProvider.AppendChange(args);
// now update the textBuffer and lineTree
if (offset == 0 && length == _rope.Length)
{
// optimize replacing the whole document
_rope.Clear();
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(0, newRopeTextSource.GetRope());
else
_rope.InsertText(0, newText.Text);
_lineManager.Rebuild();
}
else
{
_rope.RemoveRange(offset, length);
_lineManager.Remove(offset, length);
#if DEBUG
_lineTree.CheckProperties();
#endif
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(offset, newRopeTextSource.GetRope());
else
_rope.InsertText(offset, newText.Text);
_lineManager.Insert(offset, newText);
#if DEBUG
_lineTree.CheckProperties();
#endif
}
}
// update text anchors
if (offsetChangeMap == null)
{
_anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents);
}
else
{
foreach (var entry in offsetChangeMap)
{
_anchorTree.HandleTextChange(entry, delayedEvents);
}
}
_lineManager.ChangeComplete(args);
// raise delayed events after our data structures are consistent again
delayedEvents.RaiseEvents();
// fire DocumentChanged event
Changed?.Invoke(this, args);
TextChangedInternal?.Invoke(this, args);
}
#endregion
#region GetLineBy...
/// <summary>
/// Gets a read-only list of lines.
/// </summary>
/// <remarks><inheritdoc cref="DocumentLine"/></remarks>
public IList<DocumentLine> Lines => _lineTree;
/// <summary>
/// Gets a line by the line number: O(log n)
/// </summary>
public DocumentLine GetLineByNumber(int number)
{
VerifyAccess();
if (number < 1 || number > _lineTree.LineCount)
throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount);
return _lineTree.GetByNumber(number);
}
IDocumentLine IDocument.GetLineByNumber(int lineNumber)
{
return GetLineByNumber(lineNumber);
}
/// <summary>
/// Gets a document lines by offset.
/// Runtime: O(log n)
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")]
public DocumentLine GetLineByOffset(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length);
}
return _lineTree.GetByOffset(offset);
}
IDocumentLine IDocument.GetLineByOffset(int offset)
{
return GetLineByOffset(offset);
}
#endregion
#region GetOffset / GetLocation
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(TextLocation location)
{
return GetOffset(location.Line, location.Column);
}
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(int line, int column)
{
var docLine = GetLineByNumber(line);
if (column <= 0)
return docLine.Offset;
if (column > docLine.Length)
return docLine.EndOffset;
return docLine.Offset + column - 1;
}
/// <summary>
/// Gets the location from an offset.
/// </summary>
/// <seealso cref="GetOffset(TextLocation)"/>
public TextLocation GetLocation(int offset)
{
var line = GetLineByOffset(offset);
return new TextLocation(line.LineNumber, offset - line.Offset + 1);
}
#endregion
#region Line Trackers
private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>();
/// <summary>
/// Gets the list of <see cref="ILineTracker"/>s attached to this document.
/// You can add custom line trackers to this list.
/// </summary>
public IList<ILineTracker> LineTrackers
{
get
{
VerifyAccess();
return _lineTrackers;
}
}
#endregion
#region UndoStack
public UndoStack _undoStack;
/// <summary>
/// Gets the <see cref="UndoStack"/> of the document.
/// </summary>
/// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks>
public UndoStack UndoStack
{
get => _undoStack;
set
{
if (value == null)
throw new ArgumentNullException();
if (value != _undoStack)
{
_undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document
// ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress)
_undoStack = value;
OnPropertyChanged("UndoStack");
}
}
}
#endregion
#region CreateAnchor
/// <summary>
/// Creates a new <see cref="TextAnchor"/> at the specified offset.
/// </summary>
/// <inheritdoc cref="TextAnchor" select="remarks|example"/>
public TextAnchor CreateAnchor(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
return _anchorTree.CreateAnchor(offset);
}
ITextAnchor IDocument.CreateAnchor(int offset)
{
return CreateAnchor(offset);
}
#endregion
#region LineCount
/// <summary>
/// Gets the total number of lines in the document.
/// Runtime: O(1).
/// </summary>
public int LineCount
{
get
{
VerifyAccess();
return _lineTree.LineCount;
}
}
/// <summary>
/// Is raised when the LineCount property changes.
/// </summary>
public event EventHandler LineCountChanged;
#endregion
#region Debugging
[Conditional("DEBUG")]
internal void DebugVerifyAccess()
{
VerifyAccess();
}
/// <summary>
/// Gets the document lines tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetLineTreeAsString()
{
#if DEBUG
return _lineTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
/// <summary>
/// Gets the text anchor tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetTextAnchorTreeAsString()
{
#if DEBUG
return _anchorTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
#endregion
#region Service Provider
private IServiceProvider _serviceProvider;
internal IServiceProvider ServiceProvider
{
get
{
VerifyAccess();
if (_serviceProvider == null)
{
var container = new ServiceContainer();
container.AddService(this);
container.AddService<IDocument>(this);
_serviceProvider = container;
}
return _serviceProvider;
}
set
{
VerifyAccess();
_serviceProvider = value ?? throw new ArgumentNullException(nameof(value));
}
}
object IServiceProvider.GetService(Type serviceType)
{
return ServiceProvider.GetService(serviceType);
}
#endregion
#region FileName
private string _fileName;
/// <inheritdoc/>
public event EventHandler FileNameChanged;
private void OnFileNameChanged(EventArgs e)
{
FileNameChanged?.Invoke(this, e);
}
/// <inheritdoc/>
public string FileName
{
get { return _fileName; }
set
{
if (_fileName != value)
{
_fileName = value;
OnFileNameChanged(EventArgs.Empty);
}
}
}
#endregion
}
}
<MSG> Merge pull request #51 from danwalmsley/fix-thread-verification
verify access checks against thread textdocument is created on.
<DFF> @@ -26,6 +26,7 @@ using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
+using System.Threading;
namespace AvaloniaEdit.Document
{
@@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document
return _rope.ToString(offset, length);
}
+ private Thread ownerThread = Thread.CurrentThread;
+
private void VerifyAccess()
{
- Dispatcher.UIThread.VerifyAccess();
+ if(Thread.CurrentThread != ownerThread)
+ {
+ throw new InvalidOperationException("Call from invalid thread.");
+ }
}
/// <summary>
| 7 | Merge pull request #51 from danwalmsley/fix-thread-verification | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059882 | <NME> TextDocument.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
namespace AvaloniaEdit.Document
{
/// <summary>
/// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events.
/// </summary>
/// <remarks>
/// <b>Thread safety:</b>
/// <inheritdoc cref="VerifyAccess"/>
/// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para>
/// </remarks>
public sealed class TextDocument : IDocument, INotifyPropertyChanged
{
#region Thread ownership
private readonly object _lockObject = new object();
#endregion
#region Fields + Constructor
private readonly Rope<char> _rope;
private readonly DocumentLineTree _lineTree;
private readonly LineManager _lineManager;
private readonly TextAnchorTree _anchorTree;
private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider();
/// <summary>
/// Create an empty text document.
/// </summary>
public TextDocument()
: this(string.Empty.ToCharArray())
{
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(IEnumerable<char> initialText)
{
if (initialText == null)
throw new ArgumentNullException(nameof(initialText));
_rope = new Rope<char>(initialText);
_lineTree = new DocumentLineTree(this);
_lineManager = new LineManager(_lineTree, this);
_lineTrackers.CollectionChanged += delegate
{
_lineManager.UpdateListOfLineTrackers();
};
_anchorTree = new TextAnchorTree(this);
_undoStack = new UndoStack();
FireChangeEvents();
}
/// <summary>
/// Create a new text document with the specified initial text.
/// </summary>
public TextDocument(ITextSource initialText)
: this(GetTextFromTextSource(initialText))
{
}
// gets the text from a text source, directly retrieving the underlying rope where possible
private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource)
{
if (textSource == null)
throw new ArgumentNullException(nameof(textSource));
if (textSource is RopeTextSource rts)
{
return rts.GetRope();
}
if (textSource is TextDocument doc)
{
return doc._rope;
}
return textSource.Text.ToCharArray();
}
#endregion
#region Text
private void ThrowIfRangeInvalid(int offset, int length)
{
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
if (length < 0 || offset + length > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
}
/// <inheritdoc/>
public string GetText(int offset, int length)
{
VerifyAccess();
return _rope.ToString(offset, length);
}
private void VerifyAccess()
{
Dispatcher.UIThread.VerifyAccess();
}
/// <summary>
public void SetOwnerThread(Thread newOwner)
{
// We need to lock here to ensure that in the null owner case,
// only one thread succeeds in taking ownership.
lock (_lockObject) {
if (ownerThread != null) {
VerifyAccess();
}
ownerThread = newOwner;
}
}
private void VerifyAccess()
{
if(Thread.CurrentThread != ownerThread)
{
throw new InvalidOperationException("Call from invalid thread.");
}
}
/// <summary>
/// Retrieves the text for a portion of the document.
/// </summary>
public string GetText(ISegment segment)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
return GetText(segment.Offset, segment.Length);
}
/// <inheritdoc/>
public int IndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.IndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int LastIndexOf(char c, int startIndex, int count)
{
DebugVerifyAccess();
return _rope.LastIndexOf(c, startIndex, count);
}
/// <inheritdoc/>
public int IndexOfAny(char[] anyOf, int startIndex, int count)
{
DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds
return _rope.IndexOfAny(anyOf, startIndex, count);
}
/// <inheritdoc/>
public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.IndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType)
{
DebugVerifyAccess();
return _rope.LastIndexOf(searchText, startIndex, count, comparisonType);
}
/// <inheritdoc/>
public char GetCharAt(int offset)
{
DebugVerifyAccess(); // frequently called, so must be fast in release builds
return _rope[offset];
}
private WeakReference _cachedText;
/// <summary>
/// Gets/Sets the text of the whole document.
/// </summary>
public string Text
{
get
{
VerifyAccess();
var completeText = _cachedText?.Target as string;
if (completeText == null)
{
completeText = _rope.ToString();
_cachedText = new WeakReference(completeText);
}
return completeText;
}
set
{
VerifyAccess();
if (value == null)
throw new ArgumentNullException(nameof(value));
Replace(0, _rope.Length, value);
}
}
/// <summary>
/// This event is called after a group of changes is completed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextChanged;
event EventHandler IDocument.ChangeCompleted
{
add => TextChanged += value;
remove => TextChanged -= value;
}
/// <inheritdoc/>
public int TextLength
{
get
{
VerifyAccess();
return _rope.Length;
}
}
/// <summary>
/// Is raised when the TextLength property changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler TextLengthChanged;
/// <summary>
/// Is raised before the document changes.
/// </summary>
/// <remarks>
/// <para>Here is the order in which events are raised during a document update:</para>
/// <list type="bullet">
/// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description>Start of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateStarted"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="Changing"/> event is raised</description></item>
/// <item><description>The document is changed</description></item>
/// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were
/// in the deleted text portion</description></item>
/// <item><description><see cref="Changed"/> event is raised</description></item>
/// </list></item>
/// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description>
/// <list type="bullet">
/// <item><description><see cref="TextChanged"/> event is raised</description></item>
/// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item>
/// <item><description>End of change group (on undo stack)</description></item>
/// <item><description><see cref="UpdateFinished"/> event is raised</description></item>
/// </list></item>
/// </list>
/// <para>
/// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>,
/// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>.
/// </para><para>
/// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls.
/// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done.
/// </para><para>
/// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step.
/// </para>
/// </remarks>
public event EventHandler<DocumentChangeEventArgs> Changing;
// Unfortunately EventHandler<T> is invariant, so we have to use two separate events
private event EventHandler<TextChangeEventArgs> TextChangingInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanging
{
add => TextChangingInternal += value;
remove => TextChangingInternal -= value;
}
/// <summary>
/// Is raised after the document has changed.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler<DocumentChangeEventArgs> Changed;
private event EventHandler<TextChangeEventArgs> TextChangedInternal;
event EventHandler<TextChangeEventArgs> IDocument.TextChanged
{
add => TextChangedInternal += value;
remove => TextChangedInternal -= value;
}
/// <summary>
/// Creates a snapshot of the current text.
/// </summary>
/// <remarks>
/// <para>This method returns an immutable snapshot of the document, and may be safely called even when
/// the document's owner thread is concurrently modifying the document.
/// </para><para>
/// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other
/// classes implementing ITextSource.CreateSnapshot().
/// </para><para>
/// </para>
/// </remarks>
public ITextSource CreateSnapshot()
{
lock (_lockObject)
{
return new RopeTextSource(_rope, _versionProvider.CurrentVersion);
}
}
/// <summary>
/// Creates a snapshot of a part of the current text.
/// </summary>
/// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks>
public ITextSource CreateSnapshot(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextSource(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public ITextSourceVersion Version => _versionProvider.CurrentVersion;
/// <inheritdoc/>
public TextReader CreateReader()
{
lock (_lockObject)
{
return new RopeTextReader(_rope);
}
}
/// <inheritdoc/>
public TextReader CreateReader(int offset, int length)
{
lock (_lockObject)
{
return new RopeTextReader(_rope.GetRange(offset, length));
}
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer)
{
VerifyAccess();
_rope.WriteTo(writer, 0, _rope.Length);
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer, int offset, int length)
{
VerifyAccess();
_rope.WriteTo(writer, offset, length);
}
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region BeginUpdate / EndUpdate
private int _beginUpdateCount;
/// <summary>
/// Gets if an update is running.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public bool IsInUpdate
{
get
{
VerifyAccess();
return _beginUpdateCount > 0;
}
}
/// <summary>
/// Immediately calls <see cref="BeginUpdate()"/>,
/// and returns an IDisposable that calls <see cref="EndUpdate()"/>.
/// </summary>
/// <remarks><inheritdoc cref="BeginUpdate"/></remarks>
public IDisposable RunUpdate()
{
BeginUpdate();
return new CallbackOnDispose(EndUpdate);
}
/// <summary>
/// <para>Begins a group of document changes.</para>
/// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will
/// group all changes into a single action.</para>
/// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number
/// of EndUpdate calls the events resume their work.</para>
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void BeginUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot change document within another document change.");
_beginUpdateCount++;
if (_beginUpdateCount == 1)
{
_undoStack.StartUndoGroup();
UpdateStarted?.Invoke(this, EventArgs.Empty);
}
}
/// <summary>
/// Ends a group of document changes.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public void EndUpdate()
{
VerifyAccess();
if (InDocumentChanging)
throw new InvalidOperationException("Cannot end update within document change.");
if (_beginUpdateCount == 0)
throw new InvalidOperationException("No update is active.");
if (_beginUpdateCount == 1)
{
// fire change events inside the change group - event handlers might add additional
// document changes to the change group
FireChangeEvents();
_undoStack.EndUndoGroup();
_beginUpdateCount = 0;
UpdateFinished?.Invoke(this, EventArgs.Empty);
}
else
{
_beginUpdateCount -= 1;
}
}
/// <summary>
/// Occurs when a document change starts.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateStarted;
/// <summary>
/// Occurs when a document change is finished.
/// </summary>
/// <remarks><inheritdoc cref="Changing"/></remarks>
public event EventHandler UpdateFinished;
void IDocument.StartUndoableAction()
{
BeginUpdate();
}
void IDocument.EndUndoableAction()
{
EndUpdate();
}
IDisposable IDocument.OpenUndoGroup()
{
return RunUpdate();
}
#endregion
#region Fire events after update
private int _oldTextLength;
private int _oldLineCount;
private bool _fireTextChanged;
/// <summary>
/// Fires TextChanged, TextLengthChanged, LineCountChanged if required.
/// </summary>
internal void FireChangeEvents()
{
// it may be necessary to fire the event multiple times if the document is changed
// from inside the event handlers
while (_fireTextChanged)
{
_fireTextChanged = false;
TextChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("Text");
var textLength = _rope.Length;
if (textLength != _oldTextLength)
{
_oldTextLength = textLength;
TextLengthChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("TextLength");
}
var lineCount = _lineTree.LineCount;
if (lineCount != _oldLineCount)
{
_oldLineCount = lineCount;
LineCountChanged?.Invoke(this, EventArgs.Empty);
OnPropertyChanged("LineCount");
}
}
}
#endregion
#region Insert / Remove / Replace
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, string text)
{
Replace(offset, 0, new StringTextSource(text), null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <remarks>
/// Anchors positioned exactly at the insertion offset will move according to their movement type.
/// For AnchorMovementType.Default, they will move behind the inserted text.
/// The caret will also move behind the inserted text.
/// </remarks>
public void Insert(int offset, ITextSource text)
{
Replace(offset, 0, text, null);
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, new StringTextSource(text), null);
}
}
/// <summary>
/// Inserts text.
/// </summary>
/// <param name="offset">The offset at which the text is inserted.</param>
/// <param name="text">The new text.</param>
/// <param name="defaultAnchorMovementType">
/// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
/// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
/// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
/// </param>
public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType)
{
if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion)
{
Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion);
}
else
{
Replace(offset, 0, text, null);
}
}
/// <summary>
/// Removes text.
/// </summary>
public void Remove(ISegment segment)
{
Replace(segment, string.Empty);
}
/// <summary>
/// Removes text.
/// </summary>
/// <param name="offset">Starting offset of the text to be removed.</param>
/// <param name="length">Length of the text to be removed.</param>
public void Remove(int offset, int length)
{
Replace(offset, length, StringTextSource.Empty);
}
internal bool InDocumentChanging;
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, string text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
public void Replace(ISegment segment, ITextSource text)
{
if (segment == null)
throw new ArgumentNullException(nameof(segment));
Replace(segment.Offset, segment.Length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, string text)
{
Replace(offset, length, new StringTextSource(text), null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
public void Replace(int offset, int length, ITextSource text)
{
Replace(offset, length, text, null);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMappingType);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.</param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType)
{
if (text == null)
throw new ArgumentNullException(nameof(text));
// Please see OffsetChangeMappingType XML comments for details on how these modes work.
switch (offsetChangeMappingType)
{
case OffsetChangeMappingType.Normal:
Replace(offset, length, text, null);
break;
case OffsetChangeMappingType.KeepAnchorBeforeInsertion:
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(
new OffsetChangeMapEntry(offset, length, text.TextLength, false, true)));
break;
case OffsetChangeMappingType.RemoveAndInsert:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else
{
var map = new OffsetChangeMap(2)
{
new OffsetChangeMapEntry(offset, length, 0),
new OffsetChangeMapEntry(offset, 0, text.TextLength)
};
map.Freeze();
Replace(offset, length, text, map);
}
break;
case OffsetChangeMappingType.CharacterReplace:
if (length == 0 || text.TextLength == 0)
{
// only insertion or only removal?
// OffsetChangeMappingType doesn't matter, just use Normal.
Replace(offset, length, text, null);
}
else if (text.TextLength > length)
{
// look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace
// the last character
var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else if (text.TextLength < length)
{
var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false);
Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry));
}
else
{
Replace(offset, length, text, OffsetChangeMap.Empty);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value");
}
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap)
{
Replace(offset, length, new StringTextSource(text), offsetChangeMap);
}
/// <summary>
/// Replaces text.
/// </summary>
/// <param name="offset">The starting offset of the text to be replaced.</param>
/// <param name="length">The length of the text to be replaced.</param>
/// <param name="text">The new text.</param>
/// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
/// This affects how the anchors and segments inside the replaced region behave.
/// If you pass null (the default when using one of the other overloads), the offsets are changed as
/// in OffsetChangeMappingType.Normal mode.
/// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
/// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
/// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
/// DocumentChangeEventArgs instance.
/// </param>
public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap)
{
text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text));
offsetChangeMap?.Freeze();
// Ensure that all changes take place inside an update group.
// Will also take care of throwing an exception if inDocumentChanging is set.
BeginUpdate();
try
{
// protect document change against corruption by other changes inside the event handlers
InDocumentChanging = true;
try
{
// The range verification must wait until after the BeginUpdate() call because the document
// might be modified inside the UpdateStarted event.
ThrowIfRangeInvalid(offset, length);
DoReplace(offset, length, text, offsetChangeMap);
}
finally
{
InDocumentChanging = false;
}
}
finally
{
EndUpdate();
}
}
private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap)
{
if (length == 0 && newText.TextLength == 0)
return;
// trying to replace a single character in 'Normal' mode?
// for single characters, 'CharacterReplace' mode is equivalent, but more performant
// (we don't have to touch the anchorTree at all in 'CharacterReplace' mode)
if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null)
offsetChangeMap = OffsetChangeMap.Empty;
ITextSource removedText;
if (length == 0)
{
removedText = StringTextSource.Empty;
}
else if (length < 100)
{
removedText = new StringTextSource(_rope.ToString(offset, length));
}
else
{
// use a rope if the removed string is long
removedText = new RopeTextSource(_rope.GetRange(offset, length));
}
var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap);
// fire DocumentChanging event
Changing?.Invoke(this, args);
TextChangingInternal?.Invoke(this, args);
_undoStack.Push(this, args);
_cachedText = null; // reset cache of complete document text
_fireTextChanged = true;
var delayedEvents = new DelayedEvents();
lock (_lockObject)
{
// create linked list of checkpoints
_versionProvider.AppendChange(args);
// now update the textBuffer and lineTree
if (offset == 0 && length == _rope.Length)
{
// optimize replacing the whole document
_rope.Clear();
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(0, newRopeTextSource.GetRope());
else
_rope.InsertText(0, newText.Text);
_lineManager.Rebuild();
}
else
{
_rope.RemoveRange(offset, length);
_lineManager.Remove(offset, length);
#if DEBUG
_lineTree.CheckProperties();
#endif
if (newText is RopeTextSource newRopeTextSource)
_rope.InsertRange(offset, newRopeTextSource.GetRope());
else
_rope.InsertText(offset, newText.Text);
_lineManager.Insert(offset, newText);
#if DEBUG
_lineTree.CheckProperties();
#endif
}
}
// update text anchors
if (offsetChangeMap == null)
{
_anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents);
}
else
{
foreach (var entry in offsetChangeMap)
{
_anchorTree.HandleTextChange(entry, delayedEvents);
}
}
_lineManager.ChangeComplete(args);
// raise delayed events after our data structures are consistent again
delayedEvents.RaiseEvents();
// fire DocumentChanged event
Changed?.Invoke(this, args);
TextChangedInternal?.Invoke(this, args);
}
#endregion
#region GetLineBy...
/// <summary>
/// Gets a read-only list of lines.
/// </summary>
/// <remarks><inheritdoc cref="DocumentLine"/></remarks>
public IList<DocumentLine> Lines => _lineTree;
/// <summary>
/// Gets a line by the line number: O(log n)
/// </summary>
public DocumentLine GetLineByNumber(int number)
{
VerifyAccess();
if (number < 1 || number > _lineTree.LineCount)
throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount);
return _lineTree.GetByNumber(number);
}
IDocumentLine IDocument.GetLineByNumber(int lineNumber)
{
return GetLineByNumber(lineNumber);
}
/// <summary>
/// Gets a document lines by offset.
/// Runtime: O(log n)
/// </summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")]
public DocumentLine GetLineByOffset(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length);
}
return _lineTree.GetByOffset(offset);
}
IDocumentLine IDocument.GetLineByOffset(int offset)
{
return GetLineByOffset(offset);
}
#endregion
#region GetOffset / GetLocation
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(TextLocation location)
{
return GetOffset(location.Line, location.Column);
}
/// <summary>
/// Gets the offset from a text location.
/// </summary>
/// <seealso cref="GetLocation"/>
public int GetOffset(int line, int column)
{
var docLine = GetLineByNumber(line);
if (column <= 0)
return docLine.Offset;
if (column > docLine.Length)
return docLine.EndOffset;
return docLine.Offset + column - 1;
}
/// <summary>
/// Gets the location from an offset.
/// </summary>
/// <seealso cref="GetOffset(TextLocation)"/>
public TextLocation GetLocation(int offset)
{
var line = GetLineByOffset(offset);
return new TextLocation(line.LineNumber, offset - line.Offset + 1);
}
#endregion
#region Line Trackers
private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>();
/// <summary>
/// Gets the list of <see cref="ILineTracker"/>s attached to this document.
/// You can add custom line trackers to this list.
/// </summary>
public IList<ILineTracker> LineTrackers
{
get
{
VerifyAccess();
return _lineTrackers;
}
}
#endregion
#region UndoStack
public UndoStack _undoStack;
/// <summary>
/// Gets the <see cref="UndoStack"/> of the document.
/// </summary>
/// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks>
public UndoStack UndoStack
{
get => _undoStack;
set
{
if (value == null)
throw new ArgumentNullException();
if (value != _undoStack)
{
_undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document
// ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress)
_undoStack = value;
OnPropertyChanged("UndoStack");
}
}
}
#endregion
#region CreateAnchor
/// <summary>
/// Creates a new <see cref="TextAnchor"/> at the specified offset.
/// </summary>
/// <inheritdoc cref="TextAnchor" select="remarks|example"/>
public TextAnchor CreateAnchor(int offset)
{
VerifyAccess();
if (offset < 0 || offset > _rope.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture));
}
return _anchorTree.CreateAnchor(offset);
}
ITextAnchor IDocument.CreateAnchor(int offset)
{
return CreateAnchor(offset);
}
#endregion
#region LineCount
/// <summary>
/// Gets the total number of lines in the document.
/// Runtime: O(1).
/// </summary>
public int LineCount
{
get
{
VerifyAccess();
return _lineTree.LineCount;
}
}
/// <summary>
/// Is raised when the LineCount property changes.
/// </summary>
public event EventHandler LineCountChanged;
#endregion
#region Debugging
[Conditional("DEBUG")]
internal void DebugVerifyAccess()
{
VerifyAccess();
}
/// <summary>
/// Gets the document lines tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetLineTreeAsString()
{
#if DEBUG
return _lineTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
/// <summary>
/// Gets the text anchor tree in string form.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
internal string GetTextAnchorTreeAsString()
{
#if DEBUG
return _anchorTree.GetTreeAsString();
#else
return "Not available in release build.";
#endif
}
#endregion
#region Service Provider
private IServiceProvider _serviceProvider;
internal IServiceProvider ServiceProvider
{
get
{
VerifyAccess();
if (_serviceProvider == null)
{
var container = new ServiceContainer();
container.AddService(this);
container.AddService<IDocument>(this);
_serviceProvider = container;
}
return _serviceProvider;
}
set
{
VerifyAccess();
_serviceProvider = value ?? throw new ArgumentNullException(nameof(value));
}
}
object IServiceProvider.GetService(Type serviceType)
{
return ServiceProvider.GetService(serviceType);
}
#endregion
#region FileName
private string _fileName;
/// <inheritdoc/>
public event EventHandler FileNameChanged;
private void OnFileNameChanged(EventArgs e)
{
FileNameChanged?.Invoke(this, e);
}
/// <inheritdoc/>
public string FileName
{
get { return _fileName; }
set
{
if (_fileName != value)
{
_fileName = value;
OnFileNameChanged(EventArgs.Empty);
}
}
}
#endregion
}
}
<MSG> Merge pull request #51 from danwalmsley/fix-thread-verification
verify access checks against thread textdocument is created on.
<DFF> @@ -26,6 +26,7 @@ using System.Globalization;
using System.IO;
using AvaloniaEdit.Utils;
using Avalonia.Threading;
+using System.Threading;
namespace AvaloniaEdit.Document
{
@@ -129,9 +130,14 @@ namespace AvaloniaEdit.Document
return _rope.ToString(offset, length);
}
+ private Thread ownerThread = Thread.CurrentThread;
+
private void VerifyAccess()
{
- Dispatcher.UIThread.VerifyAccess();
+ if(Thread.CurrentThread != ownerThread)
+ {
+ throw new InvalidOperationException("Call from invalid thread.");
+ }
}
/// <summary>
| 7 | Merge pull request #51 from danwalmsley/fix-thread-verification | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059883 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
}
static EditingCommandHandler()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Merge pull request #53 from danwalmsley/fix/double-delete-processed
fix lastest avalonia both delete handlers get called.
<DFF> @@ -65,9 +65,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge pull request #53 from danwalmsley/fix/double-delete-processed | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059884 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
}
static EditingCommandHandler()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Merge pull request #53 from danwalmsley/fix/double-delete-processed
fix lastest avalonia both delete handlers get called.
<DFF> @@ -65,9 +65,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge pull request #53 from danwalmsley/fix/double-delete-processed | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059885 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
}
static EditingCommandHandler()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Merge pull request #53 from danwalmsley/fix/double-delete-processed
fix lastest avalonia both delete handlers get called.
<DFF> @@ -65,9 +65,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge pull request #53 from danwalmsley/fix/double-delete-processed | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059886 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
}
static EditingCommandHandler()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Merge pull request #53 from danwalmsley/fix/double-delete-processed
fix lastest avalonia both delete handlers get called.
<DFF> @@ -65,9 +65,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge pull request #53 from danwalmsley/fix/double-delete-processed | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059887 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
}
static EditingCommandHandler()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Merge pull request #53 from danwalmsley/fix/double-delete-processed
fix lastest avalonia both delete handlers get called.
<DFF> @@ -65,9 +65,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge pull request #53 from danwalmsley/fix/double-delete-processed | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059888 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
}
static EditingCommandHandler()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Merge pull request #53 from danwalmsley/fix/double-delete-processed
fix lastest avalonia both delete handlers get called.
<DFF> @@ -65,9 +65,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge pull request #53 from danwalmsley/fix/double-delete-processed | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059889 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
}
static EditingCommandHandler()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Merge pull request #53 from danwalmsley/fix/double-delete-processed
fix lastest avalonia both delete handlers get called.
<DFF> @@ -65,9 +65,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge pull request #53 from danwalmsley/fix/double-delete-processed | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059890 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
}
static EditingCommandHandler()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Merge pull request #53 from danwalmsley/fix/double-delete-processed
fix lastest avalonia both delete handlers get called.
<DFF> @@ -65,9 +65,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge pull request #53 from danwalmsley/fix/double-delete-processed | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059891 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
}
static EditingCommandHandler()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Merge pull request #53 from danwalmsley/fix/double-delete-processed
fix lastest avalonia both delete handlers get called.
<DFF> @@ -65,9 +65,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge pull request #53 from danwalmsley/fix/double-delete-processed | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059892 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
}
static EditingCommandHandler()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Merge pull request #53 from danwalmsley/fix/double-delete-processed
fix lastest avalonia both delete handlers get called.
<DFF> @@ -65,9 +65,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge pull request #53 from danwalmsley/fix/double-delete-processed | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059893 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
}
static EditingCommandHandler()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Merge pull request #53 from danwalmsley/fix/double-delete-processed
fix lastest avalonia both delete handlers get called.
<DFF> @@ -65,9 +65,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge pull request #53 from danwalmsley/fix/double-delete-processed | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059894 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
}
static EditingCommandHandler()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Merge pull request #53 from danwalmsley/fix/double-delete-processed
fix lastest avalonia both delete handlers get called.
<DFF> @@ -65,9 +65,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge pull request #53 from danwalmsley/fix/double-delete-processed | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059895 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
}
static EditingCommandHandler()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Merge pull request #53 from danwalmsley/fix/double-delete-processed
fix lastest avalonia both delete handlers get called.
<DFF> @@ -65,9 +65,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge pull request #53 from danwalmsley/fix/double-delete-processed | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059896 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
}
static EditingCommandHandler()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Merge pull request #53 from danwalmsley/fix/double-delete-processed
fix lastest avalonia both delete handlers get called.
<DFF> @@ -65,9 +65,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge pull request #53 from danwalmsley/fix/double-delete-processed | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059897 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
}
static EditingCommandHandler()
{
// TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back,
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = true;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> Merge pull request #53 from danwalmsley/fix/double-delete-processed
fix lastest avalonia both delete handlers get called.
<DFF> @@ -65,9 +65,7 @@ namespace AvaloniaEdit.Editing
}
static EditingCommandHandler()
- {
- // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
+ {
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
| 1 | Merge pull request #53 from danwalmsley/fix/double-delete-processed | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059898 | <NME> README.md
<BEF> # FruitMachine [](https://travis-ci.com/ftlabs/fruitmachine) [](https://coveralls.io/r/ftlabs/fruitmachine)
A lightweight component layout engine for client and server.
FruitMachine is designed to build rich interactive layouts from modular, reusable components. It's light and unopinionated so that it can be applied to almost any layout problem. FruitMachine is currently powering the [FT Web App](http://apps.ft.com/ftwebapp/).
```js
// Define a module
var Apple = fruitmachine.define({
name: 'apple',
template: function(){ return 'hello' }
});
// Create a module
var apple = new Apple();
// Render it
apple.render();
//=> <div class="apple">hello</div>
```
## Contents
- [Introduction](docs/introduction.md)
- [Getting started](docs/getting-started.md)
- [Defining modules](docs/defining-modules.md)
- [Instantiation](docs/instantiation.md)
- [Queries](docs/queries.md)
- [Templates](docs/templates.md)
- [Template markup](docs/template-markup.md)
- [El](docs/view-el.md)
- [Helpers](docs/helpers.md)
- [DOM injection](docs/dom-injection.md)
- [Extending](docs/extending.md)
## Why not Backbone?
## Documentation
- [Introduction](docs/introduction.md)
- [Getting started](docs/getting-started.md)
- [Defining modules](docs/defining-modules.md)
- [Slots](docs/slots.md)
- [View assembly](docs/layout-assembly.md)
- [Instantiation](docs/module-instantiation.md)
- [Templates](docs/templates.md)
- [Template markup](docs/template-markup.md)
- [Rendering](docs/rendering.md)
- [DOM injection](docs/injection.md)
- [The module element](docs/module-el.md)
- [Queries](docs/queries.md)
- [Helpers](docs/module-helpers.md)
- [Removing & destroying](docs/removing-and-destroying.md)
- [Extending](docs/extending-modules.md)
- [Server-side rendering](docs/server-side-rendering.md)
- [API](docs/api.md)
- [Events](docs/events.md)
## Tests
#### With PhantomJS
```
$ npm install
$ npm test
```
#### Without PhantomJS
```
$ node_modules/.bin/buster-static
```
...then visit http://localhost:8282/ in browser
## Author
- **Wilson Page** - [@wilsonpage](http://github.com/wilsonpage)
## Contributors
- **Wilson Page** - [@wilsonpage](http://github.com/wilsonpage)
- **Matt Andrews** - [@matthew-andrews](http://github.com/matthew-andrews)
## License
Copyright (c) 2018 The Financial Times Limited
Licensed under the MIT license.
## Credits and collaboration
FruitMachine is largely unmaintained/finished. All open source code released by FT Labs is licenced under the MIT licence. We welcome comments, feedback and suggestions. Please feel free to raise an issue or pull request.
<MSG> Updated readme
<DFF> @@ -19,23 +19,27 @@ apple.el.outerHTML;
//=> <div class="apple">hello</div>
```
-## Contents
-
-- [Introduction](docs/introduction.md)
-- [Getting started](docs/getting-started.md)
-- [Defining modules](docs/defining-modules.md)
-- [Instantiation](docs/instantiation.md)
-- [Queries](docs/queries.md)
-- [Templates](docs/templates.md)
-- [Template markup](docs/template-markup.md)
-- [El](docs/view-el.md)
-- [Helpers](docs/helpers.md)
-- [DOM injection](docs/dom-injection.md)
-- [Extending](docs/extending.md)
-
+## Examples
+- [Article viewer](http://wilsonpage.github.io/fruitmachine/examples/1a/)
+- [TODO](http://wilsonpage.github.io/fruitmachine/examples/todo/)
+## Contents
+- [Introduction](https://github.com/wilsonpage/fruitmachine/tree/master/docs/introduction.md)
+- [Getting started](https://github.com/wilsonpage/fruitmachine/tree/master/docs/getting-started.md)
+- [Defining modules](https://github.com/wilsonpage/fruitmachine/tree/master/docs/view-defining-modules.md)
+- [View assembly](https://github.com/wilsonpage/fruitmachine/tree/master/docs/view-assembly.md)
+- [Instantiation](https://github.com/wilsonpage/fruitmachine/tree/master/docs/view-instantiation.md)
+- [Queries](https://github.com/wilsonpage/fruitmachine/tree/master/docs/view-queries.md)
+- [Templates](https://github.com/wilsonpage/fruitmachine/tree/master/docs/view-templates.md)
+- [Template markup](https://github.com/wilsonpage/fruitmachine/tree/master/docs/view-template-markup.md)
+- [Rendering](https://github.com/wilsonpage/fruitmachine/tree/master/docs/view-rendering.md)
+- [El](https://github.com/wilsonpage/fruitmachine/tree/master/docs/view-el.md)
+- [Helpers](https://github.com/wilsonpage/fruitmachine/tree/master/docs/view-helpers.md)
+- [DOM injection](https://github.com/wilsonpage/fruitmachine/tree/master/docs/view-injection.md)
+- [Removing & destroying](https://github.com/wilsonpage/fruitmachine/tree/master/docs/view-removing-and-destroying.md)
+- [Extending](https://github.com/wilsonpage/fruitmachine/tree/master/docs/view-extending.md)
## Why not Backbone?
| 18 | Updated readme | 14 | .md | md | mit | ftlabs/fruitmachine |
10059899 | <NME> TextEditorModelTests.cs
<BEF> using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using NUnit.Framework;
namespace AvaloniaEdit.Tests.TextMate
{
[TestFixture]
internal class TextEditorModelTests
{
[Test]
public void Lines_Should_Have_Valid_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
}
[Test]
public void Lines_Should_Have_Valid_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Length()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", textEditorModel.GetLineText(2));
Assert.AreEqual("birdie", textEditorModel.GetLineText(3));
}
[Test]
public void Removing_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Document_Lines_Count_Should_Match_Model_Lines_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Insert_Document_Line_Should_Insert_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Remove_Document_Line_Should_Remove_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Replace_Text_Of_Same_Length_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "P");
Assert.AreEqual("Puppy", textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
}
}
<MSG> Merge pull request #225 from AvaloniaUI/fix-221
Handle batch documents updates
<DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
@@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
+
+ [Test]
+ public void Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
+
+ [Test]
+ public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.BeginUpdate();
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNotNull(textEditorModel.InvalidRange,
+ "InvalidRange should not be null");
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
}
}
| 99 | Merge pull request #225 from AvaloniaUI/fix-221 | 15 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059900 | <NME> TextEditorModelTests.cs
<BEF> using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using NUnit.Framework;
namespace AvaloniaEdit.Tests.TextMate
{
[TestFixture]
internal class TextEditorModelTests
{
[Test]
public void Lines_Should_Have_Valid_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
}
[Test]
public void Lines_Should_Have_Valid_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Length()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", textEditorModel.GetLineText(2));
Assert.AreEqual("birdie", textEditorModel.GetLineText(3));
}
[Test]
public void Removing_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Document_Lines_Count_Should_Match_Model_Lines_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Insert_Document_Line_Should_Insert_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Remove_Document_Line_Should_Remove_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Replace_Text_Of_Same_Length_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "P");
Assert.AreEqual("Puppy", textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
}
}
<MSG> Merge pull request #225 from AvaloniaUI/fix-221
Handle batch documents updates
<DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
@@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
+
+ [Test]
+ public void Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
+
+ [Test]
+ public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.BeginUpdate();
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNotNull(textEditorModel.InvalidRange,
+ "InvalidRange should not be null");
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
}
}
| 99 | Merge pull request #225 from AvaloniaUI/fix-221 | 15 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059901 | <NME> TextEditorModelTests.cs
<BEF> using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using NUnit.Framework;
namespace AvaloniaEdit.Tests.TextMate
{
[TestFixture]
internal class TextEditorModelTests
{
[Test]
public void Lines_Should_Have_Valid_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
}
[Test]
public void Lines_Should_Have_Valid_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Length()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", textEditorModel.GetLineText(2));
Assert.AreEqual("birdie", textEditorModel.GetLineText(3));
}
[Test]
public void Removing_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Document_Lines_Count_Should_Match_Model_Lines_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Insert_Document_Line_Should_Insert_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Remove_Document_Line_Should_Remove_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Replace_Text_Of_Same_Length_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "P");
Assert.AreEqual("Puppy", textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
}
}
<MSG> Merge pull request #225 from AvaloniaUI/fix-221
Handle batch documents updates
<DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
@@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
+
+ [Test]
+ public void Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
+
+ [Test]
+ public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.BeginUpdate();
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNotNull(textEditorModel.InvalidRange,
+ "InvalidRange should not be null");
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
}
}
| 99 | Merge pull request #225 from AvaloniaUI/fix-221 | 15 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059902 | <NME> TextEditorModelTests.cs
<BEF> using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using NUnit.Framework;
namespace AvaloniaEdit.Tests.TextMate
{
[TestFixture]
internal class TextEditorModelTests
{
[Test]
public void Lines_Should_Have_Valid_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
}
[Test]
public void Lines_Should_Have_Valid_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Length()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", textEditorModel.GetLineText(2));
Assert.AreEqual("birdie", textEditorModel.GetLineText(3));
}
[Test]
public void Removing_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Document_Lines_Count_Should_Match_Model_Lines_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Insert_Document_Line_Should_Insert_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Remove_Document_Line_Should_Remove_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Replace_Text_Of_Same_Length_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "P");
Assert.AreEqual("Puppy", textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
}
}
<MSG> Merge pull request #225 from AvaloniaUI/fix-221
Handle batch documents updates
<DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
@@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
+
+ [Test]
+ public void Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
+
+ [Test]
+ public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.BeginUpdate();
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNotNull(textEditorModel.InvalidRange,
+ "InvalidRange should not be null");
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
}
}
| 99 | Merge pull request #225 from AvaloniaUI/fix-221 | 15 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059903 | <NME> TextEditorModelTests.cs
<BEF> using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using NUnit.Framework;
namespace AvaloniaEdit.Tests.TextMate
{
[TestFixture]
internal class TextEditorModelTests
{
[Test]
public void Lines_Should_Have_Valid_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
}
[Test]
public void Lines_Should_Have_Valid_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Length()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", textEditorModel.GetLineText(2));
Assert.AreEqual("birdie", textEditorModel.GetLineText(3));
}
[Test]
public void Removing_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Document_Lines_Count_Should_Match_Model_Lines_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Insert_Document_Line_Should_Insert_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Remove_Document_Line_Should_Remove_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Replace_Text_Of_Same_Length_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "P");
Assert.AreEqual("Puppy", textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
}
}
<MSG> Merge pull request #225 from AvaloniaUI/fix-221
Handle batch documents updates
<DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
@@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
+
+ [Test]
+ public void Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
+
+ [Test]
+ public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.BeginUpdate();
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNotNull(textEditorModel.InvalidRange,
+ "InvalidRange should not be null");
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
}
}
| 99 | Merge pull request #225 from AvaloniaUI/fix-221 | 15 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059904 | <NME> TextEditorModelTests.cs
<BEF> using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using NUnit.Framework;
namespace AvaloniaEdit.Tests.TextMate
{
[TestFixture]
internal class TextEditorModelTests
{
[Test]
public void Lines_Should_Have_Valid_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
}
[Test]
public void Lines_Should_Have_Valid_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Length()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", textEditorModel.GetLineText(2));
Assert.AreEqual("birdie", textEditorModel.GetLineText(3));
}
[Test]
public void Removing_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Document_Lines_Count_Should_Match_Model_Lines_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Insert_Document_Line_Should_Insert_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Remove_Document_Line_Should_Remove_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Replace_Text_Of_Same_Length_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "P");
Assert.AreEqual("Puppy", textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
}
}
<MSG> Merge pull request #225 from AvaloniaUI/fix-221
Handle batch documents updates
<DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
@@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
+
+ [Test]
+ public void Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
+
+ [Test]
+ public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.BeginUpdate();
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNotNull(textEditorModel.InvalidRange,
+ "InvalidRange should not be null");
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
}
}
| 99 | Merge pull request #225 from AvaloniaUI/fix-221 | 15 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059905 | <NME> TextEditorModelTests.cs
<BEF> using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using NUnit.Framework;
namespace AvaloniaEdit.Tests.TextMate
{
[TestFixture]
internal class TextEditorModelTests
{
[Test]
public void Lines_Should_Have_Valid_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
}
[Test]
public void Lines_Should_Have_Valid_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Length()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", textEditorModel.GetLineText(2));
Assert.AreEqual("birdie", textEditorModel.GetLineText(3));
}
[Test]
public void Removing_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Document_Lines_Count_Should_Match_Model_Lines_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Insert_Document_Line_Should_Insert_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Remove_Document_Line_Should_Remove_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Replace_Text_Of_Same_Length_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "P");
Assert.AreEqual("Puppy", textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
}
}
<MSG> Merge pull request #225 from AvaloniaUI/fix-221
Handle batch documents updates
<DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
@@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
+
+ [Test]
+ public void Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
+
+ [Test]
+ public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.BeginUpdate();
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNotNull(textEditorModel.InvalidRange,
+ "InvalidRange should not be null");
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
}
}
| 99 | Merge pull request #225 from AvaloniaUI/fix-221 | 15 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059906 | <NME> TextEditorModelTests.cs
<BEF> using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using NUnit.Framework;
namespace AvaloniaEdit.Tests.TextMate
{
[TestFixture]
internal class TextEditorModelTests
{
[Test]
public void Lines_Should_Have_Valid_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
}
[Test]
public void Lines_Should_Have_Valid_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Length()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", textEditorModel.GetLineText(2));
Assert.AreEqual("birdie", textEditorModel.GetLineText(3));
}
[Test]
public void Removing_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Document_Lines_Count_Should_Match_Model_Lines_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Insert_Document_Line_Should_Insert_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Remove_Document_Line_Should_Remove_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Replace_Text_Of_Same_Length_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "P");
Assert.AreEqual("Puppy", textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
}
}
<MSG> Merge pull request #225 from AvaloniaUI/fix-221
Handle batch documents updates
<DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
@@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
+
+ [Test]
+ public void Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
+
+ [Test]
+ public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.BeginUpdate();
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNotNull(textEditorModel.InvalidRange,
+ "InvalidRange should not be null");
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
}
}
| 99 | Merge pull request #225 from AvaloniaUI/fix-221 | 15 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059907 | <NME> TextEditorModelTests.cs
<BEF> using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using NUnit.Framework;
namespace AvaloniaEdit.Tests.TextMate
{
[TestFixture]
internal class TextEditorModelTests
{
[Test]
public void Lines_Should_Have_Valid_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
}
[Test]
public void Lines_Should_Have_Valid_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Length()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", textEditorModel.GetLineText(2));
Assert.AreEqual("birdie", textEditorModel.GetLineText(3));
}
[Test]
public void Removing_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Document_Lines_Count_Should_Match_Model_Lines_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Insert_Document_Line_Should_Insert_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Remove_Document_Line_Should_Remove_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Replace_Text_Of_Same_Length_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "P");
Assert.AreEqual("Puppy", textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
}
}
<MSG> Merge pull request #225 from AvaloniaUI/fix-221
Handle batch documents updates
<DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
@@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
+
+ [Test]
+ public void Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
+
+ [Test]
+ public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.BeginUpdate();
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNotNull(textEditorModel.InvalidRange,
+ "InvalidRange should not be null");
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
}
}
| 99 | Merge pull request #225 from AvaloniaUI/fix-221 | 15 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059908 | <NME> TextEditorModelTests.cs
<BEF> using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using NUnit.Framework;
namespace AvaloniaEdit.Tests.TextMate
{
[TestFixture]
internal class TextEditorModelTests
{
[Test]
public void Lines_Should_Have_Valid_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
}
[Test]
public void Lines_Should_Have_Valid_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Length()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", textEditorModel.GetLineText(2));
Assert.AreEqual("birdie", textEditorModel.GetLineText(3));
}
[Test]
public void Removing_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Document_Lines_Count_Should_Match_Model_Lines_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Insert_Document_Line_Should_Insert_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Remove_Document_Line_Should_Remove_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Replace_Text_Of_Same_Length_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "P");
Assert.AreEqual("Puppy", textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
}
}
<MSG> Merge pull request #225 from AvaloniaUI/fix-221
Handle batch documents updates
<DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
@@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
+
+ [Test]
+ public void Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
+
+ [Test]
+ public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.BeginUpdate();
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNotNull(textEditorModel.InvalidRange,
+ "InvalidRange should not be null");
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
}
}
| 99 | Merge pull request #225 from AvaloniaUI/fix-221 | 15 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059909 | <NME> TextEditorModelTests.cs
<BEF> using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using NUnit.Framework;
namespace AvaloniaEdit.Tests.TextMate
{
[TestFixture]
internal class TextEditorModelTests
{
[Test]
public void Lines_Should_Have_Valid_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
}
[Test]
public void Lines_Should_Have_Valid_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Length()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", textEditorModel.GetLineText(2));
Assert.AreEqual("birdie", textEditorModel.GetLineText(3));
}
[Test]
public void Removing_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Document_Lines_Count_Should_Match_Model_Lines_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Insert_Document_Line_Should_Insert_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Remove_Document_Line_Should_Remove_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Replace_Text_Of_Same_Length_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "P");
Assert.AreEqual("Puppy", textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
}
}
<MSG> Merge pull request #225 from AvaloniaUI/fix-221
Handle batch documents updates
<DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
@@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
+
+ [Test]
+ public void Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
+
+ [Test]
+ public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.BeginUpdate();
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNotNull(textEditorModel.InvalidRange,
+ "InvalidRange should not be null");
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
}
}
| 99 | Merge pull request #225 from AvaloniaUI/fix-221 | 15 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059910 | <NME> TextEditorModelTests.cs
<BEF> using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using NUnit.Framework;
namespace AvaloniaEdit.Tests.TextMate
{
[TestFixture]
internal class TextEditorModelTests
{
[Test]
public void Lines_Should_Have_Valid_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
}
[Test]
public void Lines_Should_Have_Valid_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Length()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", textEditorModel.GetLineText(2));
Assert.AreEqual("birdie", textEditorModel.GetLineText(3));
}
[Test]
public void Removing_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Document_Lines_Count_Should_Match_Model_Lines_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Insert_Document_Line_Should_Insert_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Remove_Document_Line_Should_Remove_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Replace_Text_Of_Same_Length_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "P");
Assert.AreEqual("Puppy", textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
}
}
<MSG> Merge pull request #225 from AvaloniaUI/fix-221
Handle batch documents updates
<DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
@@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
+
+ [Test]
+ public void Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
+
+ [Test]
+ public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.BeginUpdate();
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNotNull(textEditorModel.InvalidRange,
+ "InvalidRange should not be null");
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
}
}
| 99 | Merge pull request #225 from AvaloniaUI/fix-221 | 15 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059911 | <NME> TextEditorModelTests.cs
<BEF> using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using NUnit.Framework;
namespace AvaloniaEdit.Tests.TextMate
{
[TestFixture]
internal class TextEditorModelTests
{
[Test]
public void Lines_Should_Have_Valid_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
}
[Test]
public void Lines_Should_Have_Valid_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Length()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", textEditorModel.GetLineText(2));
Assert.AreEqual("birdie", textEditorModel.GetLineText(3));
}
[Test]
public void Removing_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Document_Lines_Count_Should_Match_Model_Lines_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Insert_Document_Line_Should_Insert_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Remove_Document_Line_Should_Remove_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Replace_Text_Of_Same_Length_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "P");
Assert.AreEqual("Puppy", textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
}
}
<MSG> Merge pull request #225 from AvaloniaUI/fix-221
Handle batch documents updates
<DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
@@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
+
+ [Test]
+ public void Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
+
+ [Test]
+ public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.BeginUpdate();
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNotNull(textEditorModel.InvalidRange,
+ "InvalidRange should not be null");
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
}
}
| 99 | Merge pull request #225 from AvaloniaUI/fix-221 | 15 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059912 | <NME> TextEditorModelTests.cs
<BEF> using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using NUnit.Framework;
namespace AvaloniaEdit.Tests.TextMate
{
[TestFixture]
internal class TextEditorModelTests
{
[Test]
public void Lines_Should_Have_Valid_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
}
[Test]
public void Lines_Should_Have_Valid_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Length()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", textEditorModel.GetLineText(2));
Assert.AreEqual("birdie", textEditorModel.GetLineText(3));
}
[Test]
public void Removing_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Document_Lines_Count_Should_Match_Model_Lines_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Insert_Document_Line_Should_Insert_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Remove_Document_Line_Should_Remove_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Replace_Text_Of_Same_Length_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "P");
Assert.AreEqual("Puppy", textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
}
}
<MSG> Merge pull request #225 from AvaloniaUI/fix-221
Handle batch documents updates
<DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
@@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
+
+ [Test]
+ public void Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
+
+ [Test]
+ public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.BeginUpdate();
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNotNull(textEditorModel.InvalidRange,
+ "InvalidRange should not be null");
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
}
}
| 99 | Merge pull request #225 from AvaloniaUI/fix-221 | 15 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059913 | <NME> TextEditorModelTests.cs
<BEF> using AvaloniaEdit.Document;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.TextMate;
using NUnit.Framework;
namespace AvaloniaEdit.Tests.TextMate
{
[TestFixture]
internal class TextEditorModelTests
{
[Test]
public void Lines_Should_Have_Valid_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
}
[Test]
public void Lines_Should_Have_Valid_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual("puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0));
Assert.AreEqual("pussy", textEditorModel.GetLineText(1));
Assert.AreEqual("birdie", textEditorModel.GetLineText(2));
}
[Test]
public void Editing_Line_Should_Update_The_Line_Length()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0));
}
[Test]
public void Inserting_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
Assert.AreEqual("lion", textEditorModel.GetLineText(0));
Assert.AreEqual("puppy", textEditorModel.GetLineText(1));
Assert.AreEqual("pussy", textEditorModel.GetLineText(2));
Assert.AreEqual("birdie", textEditorModel.GetLineText(3));
}
[Test]
public void Removing_Line_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
Assert.AreEqual("pussy", textEditorModel.GetLineText(0));
Assert.AreEqual("birdie", textEditorModel.GetLineText(1));
}
[Test]
public void Document_Lines_Count_Should_Match_Model_Lines_Count()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "cutty ");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Insert_Document_Line_Should_Insert_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Insert(0, "lion\n");
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Remove_Document_Line_Should_Remove_Model_Line()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Remove(
document.Lines[0].Offset,
document.Lines[0].TotalLength);
int count = 0;
textEditorModel.ForEach((m) => count++);
Assert.AreEqual(document.LineCount, count);
}
[Test]
public void Replace_Text_Of_Same_Length_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "P");
Assert.AreEqual("Puppy", textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
document.Replace(0, 1, "\n");
Assert.AreEqual("", textEditorModel.GetLineText(0));
}
[Test]
public void Remove_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = string.Empty;
Assert.AreEqual(1, textEditorModel.GetNumberOfLines());
Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0));
}
[Test]
public void Replace_Document_Text_Should_Update_Line_Contents()
{
TextView textView = new TextView();
TextDocument document = new TextDocument();
TextEditorModel textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
Assert.AreEqual(3, textEditorModel.GetNumberOfLines());
document.Text = "one\ntwo\nthree\nfour";
Assert.AreEqual(4, textEditorModel.GetNumberOfLines());
Assert.AreEqual("one", textEditorModel.GetLineText(0));
Assert.AreEqual("two", textEditorModel.GetLineText(1));
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
}
}
<MSG> Merge pull request #225 from AvaloniaUI/fix-221
Handle batch documents updates
<DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\r\npussy\r\nbirdie";
@@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate
TextView textView = new TextView();
TextDocument document = new TextDocument();
- TextEditorModel textEditorModel = new TextEditorModel(
+ using var textEditorModel = new TextEditorModel(
textView, document, null);
document.Text = "puppy\npussy\nbirdie";
@@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate
Assert.AreEqual("three", textEditorModel.GetLineText(2));
Assert.AreEqual("four", textEditorModel.GetLineText(3));
}
+
+ [Test]
+ public void Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
+
+ [Test]
+ public void Nested_Batch_Document_Changes_Should_Invalidate_Lines()
+ {
+ TextView textView = new TextView();
+ TextDocument document = new TextDocument();
+
+ using var textEditorModel = new TextEditorModel(
+ textView, document, null);
+
+ document.Text = "puppy\npuppy\npuppy";
+
+ document.BeginUpdate();
+
+ document.Insert(0, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 1");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 1");
+
+ document.BeginUpdate();
+ document.Insert(7, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 2");
+ Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 2");
+
+ document.Insert(14, "*");
+ Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine,
+ "Wrong InvalidRange.StartLine 3");
+ Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine,
+ "Wrong InvalidRange.EndLine 3");
+
+ document.EndUpdate();
+ Assert.IsNotNull(textEditorModel.InvalidRange,
+ "InvalidRange should not be null");
+ document.EndUpdate();
+ Assert.IsNull(textEditorModel.InvalidRange,
+ "InvalidRange should be null");
+
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(0));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(1));
+ Assert.AreEqual("*puppy", textEditorModel.GetLineText(2));
+ }
}
}
| 99 | Merge pull request #225 from AvaloniaUI/fix-221 | 15 | .cs | Tests/TextMate/TextEditorModelTests | mit | AvaloniaUI/AvaloniaEdit |
10059914 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines
fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059915 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines
fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059916 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines
fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059917 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines
fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059918 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines
fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059919 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines
fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059920 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines
fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059921 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines
fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059922 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines
fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059923 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines
fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059924 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines
fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059925 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines
fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059926 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines
fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059927 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines
fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059928 | <NME> HeightTree.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
/// Red-black tree similar to DocumentLineTree, augmented with collapsing and height data.
/// </summary>
internal sealed class HeightTree : ILineTracker, IDisposable
{
// TODO: Optimize this. This tree takes alot of memory.
// (56 bytes for HeightTreeNode
// We should try to get rid of the dictionary and find height nodes per index. (DONE!)
// And we might do much better by compressing lines with the same height into a single node.
// That would also improve load times because we would always start with just a single node.
/* Idea:
class NewHeightTreeNode {
int totalCount; // =count+left.count+right.count
int count; // one node can represent multiple lines
double height; // height of each line in this node
double totalHeight; // =(collapsedSections!=null?0:height*count) + left.totalHeight + right.totalHeight
List<CollapsedSection> collapsedSections; // sections holding this line collapsed
// no "nodeCollapsedSections"/"totalCollapsedSections":
NewHeightTreeNode left, right, parent;
bool color;
}
totalCollapsedSections: are hard to update and not worth the effort. O(n log n) isn't too bad for
collapsing/uncollapsing, especially when compression reduces the n.
*/
#region Constructor
private readonly TextDocument _document;
private HeightTreeNode _root;
private WeakLineTracker _weakLineTracker;
public HeightTree(TextDocument document, double defaultLineHeight)
{
this._document = document;
_weakLineTracker = WeakLineTracker.Register(document, this);
this.DefaultLineHeight = defaultLineHeight;
RebuildDocument();
}
public void Dispose()
{
if (_weakLineTracker != null)
_weakLineTracker.Deregister();
this._root = null;
this._weakLineTracker = null;
}
public bool IsDisposed {
get {
return _root == null;
}
}
private double _defaultLineHeight;
public double DefaultLineHeight {
get { return _defaultLineHeight; }
set {
var oldValue = _defaultLineHeight;
if (oldValue == value)
return;
_defaultLineHeight = value;
// update the stored value in all nodes:
foreach (var node in AllNodes) {
if (node.LineNode.Height == oldValue) {
node.LineNode.Height = value;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
}
}
}
private HeightTreeNode GetNode(DocumentLine ls)
{
return GetNodeByIndex(ls.LineNumber - 1);
}
#endregion
#region RebuildDocument
void ILineTracker.ChangeComplete(DocumentChangeEventArgs e)
{
}
void ILineTracker.SetLineLength(DocumentLine ls, int newTotalLength)
{
}
/// <summary>
/// Rebuild the tree, in O(n).
/// </summary>
public void RebuildDocument()
{
foreach (var s in GetAllCollapsedSections()) {
s.Start = null;
s.End = null;
}
var nodes = new HeightTreeNode[_document.LineCount];
var lineNumber = 0;
foreach (var ls in _document.Lines) {
nodes[lineNumber++] = new HeightTreeNode(ls, _defaultLineHeight);
}
Debug.Assert(nodes.Length > 0);
// now build the corresponding balanced tree
var height = DocumentLineTree.GetTreeHeight(nodes.Length);
Debug.WriteLine("HeightTree will have height: " + height);
_root = BuildTree(nodes, 0, nodes.Length, height);
_root.Color = Black;
#if DEBUG
CheckProperties();
#endif
}
/// <summary>
/// build a tree from a list of nodes
/// </summary>
private HeightTreeNode BuildTree(HeightTreeNode[] nodes, int start, int end, int subtreeHeight)
{
Debug.Assert(start <= end);
if (start == end) {
return null;
}
var middle = (start + end) / 2;
var node = nodes[middle];
node.Left = BuildTree(nodes, start, middle, subtreeHeight - 1);
node.Right = BuildTree(nodes, middle + 1, end, subtreeHeight - 1);
if (node.Left != null) node.Left.Parent = node;
if (node.Right != null) node.Right.Parent = node;
if (subtreeHeight == 1)
node.Color = Red;
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.None);
return node;
}
#endregion
#region Insert/Remove lines
void ILineTracker.BeforeRemoveLine(DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null) {
foreach (var cs in node.LineNode.CollapsedSections.ToArray()) {
if (cs.Start == line && cs.End == line) {
cs.Start = null;
cs.End = null;
} else if (cs.Start == line) {
Uncollapse(cs);
cs.Start = line.NextLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
} else if (cs.End == line) {
Uncollapse(cs);
cs.End = line.PreviousLine;
AddCollapsedSection(cs, cs.End.LineNumber - cs.Start.LineNumber + 1);
}
}
}
BeginRemoval();
RemoveNode(node);
// clear collapsedSections from removed line: prevent damage if removed line is in "nodesToCheckForMerging"
node.LineNode.CollapsedSections = null;
EndRemoval();
}
// void ILineTracker.AfterRemoveLine(DocumentLine line)
// {
//
// }
void ILineTracker.LineInserted(DocumentLine insertionPos, DocumentLine newLine)
{
InsertAfter(GetNode(insertionPos), newLine);
#if DEBUG
CheckProperties();
#endif
}
private HeightTreeNode InsertAfter(HeightTreeNode node, DocumentLine newLine)
{
var newNode = new HeightTreeNode(newLine, _defaultLineHeight);
if (node.Right == null) {
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly after node - so copy all collapsedSections
// that do not end at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.End != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsRight(node, newNode);
} else {
node = node.Right.LeftMost;
if (node.LineNode.CollapsedSections != null) {
// we are inserting directly before node - so copy all collapsedSections
// that do not start at node.
foreach (var cs in node.LineNode.CollapsedSections) {
if (cs.Start != node.DocumentLine)
newNode.AddDirectlyCollapsed(cs);
}
}
InsertAsLeft(node, newNode);
}
return newNode;
}
#endregion
#region Rotation callbacks
private enum UpdateAfterChildrenChangeRecursionMode
{
None,
IfRequired,
WholeBranch
}
private static void UpdateAfterChildrenChange(HeightTreeNode node)
{
UpdateAugmentedData(node, UpdateAfterChildrenChangeRecursionMode.IfRequired);
}
private static void UpdateAugmentedData(HeightTreeNode node, UpdateAfterChildrenChangeRecursionMode mode)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.Left != null) {
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
}
if (node.Right != null) {
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
}
if (node.IsDirectlyCollapsed)
totalHeight = 0;
if (totalCount != node.TotalCount
|| !totalHeight.IsClose(node.TotalHeight)
|| mode == UpdateAfterChildrenChangeRecursionMode.WholeBranch)
{
node.TotalCount = totalCount;
node.TotalHeight = totalHeight;
if (node.Parent != null && mode != UpdateAfterChildrenChangeRecursionMode.None)
UpdateAugmentedData(node.Parent, mode);
}
}
private void UpdateAfterRotateLeft(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Right != null)
node.Parent.Right.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Right != null)
node.Right.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
private void UpdateAfterRotateRight(HeightTreeNode node)
{
// node = old parent
// node.parent = pivot, new parent
var collapsedP = node.Parent.CollapsedSections;
var collapsedQ = node.CollapsedSections;
// move collapsedSections from old parent to new parent
node.Parent.CollapsedSections = collapsedQ;
node.CollapsedSections = null;
// split the collapsedSections from the new parent into its old children:
if (collapsedP != null) {
foreach (var cs in collapsedP) {
if (node.Parent.Left != null)
node.Parent.Left.AddDirectlyCollapsed(cs);
node.Parent.LineNode.AddDirectlyCollapsed(cs);
if (node.Left != null)
node.Left.AddDirectlyCollapsed(cs);
}
}
MergeCollapsedSectionsIfPossible(node);
UpdateAfterChildrenChange(node);
// not required: rotations only happen on insertions/deletions
// -> totalCount changes -> the parent is always updated
//UpdateAfterChildrenChange(node.parent);
}
// node removal:
// a node in the middle of the tree is removed as following:
// its successor is removed
// it is replaced with its successor
private void BeforeNodeRemove(HeightTreeNode removedNode)
{
Debug.Assert(removedNode.Left == null || removedNode.Right == null);
var collapsed = removedNode.CollapsedSections;
if (collapsed != null) {
var childNode = removedNode.Left ?? removedNode.Right;
if (childNode != null) {
foreach (var cs in collapsed)
childNode.AddDirectlyCollapsed(cs);
}
}
if (removedNode.Parent != null)
MergeCollapsedSectionsIfPossible(removedNode.Parent);
}
private void BeforeNodeReplace(HeightTreeNode removedNode, HeightTreeNode newNode, HeightTreeNode newNodeOldParent)
{
Debug.Assert(removedNode != null);
Debug.Assert(newNode != null);
while (newNodeOldParent != removedNode) {
if (newNodeOldParent.CollapsedSections != null) {
foreach (var cs in newNodeOldParent.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNodeOldParent = newNodeOldParent.Parent;
}
if (newNode.CollapsedSections != null) {
foreach (var cs in newNode.CollapsedSections) {
newNode.LineNode.AddDirectlyCollapsed(cs);
}
}
newNode.CollapsedSections = removedNode.CollapsedSections;
MergeCollapsedSectionsIfPossible(newNode);
}
private bool _inRemoval;
private List<HeightTreeNode> _nodesToCheckForMerging;
private void BeginRemoval()
{
Debug.Assert(!_inRemoval);
if (_nodesToCheckForMerging == null) {
_nodesToCheckForMerging = new List<HeightTreeNode>();
}
_inRemoval = true;
}
private void EndRemoval()
{
Debug.Assert(_inRemoval);
_inRemoval = false;
foreach (var node in _nodesToCheckForMerging) {
MergeCollapsedSectionsIfPossible(node);
}
_nodesToCheckForMerging.Clear();
}
private void MergeCollapsedSectionsIfPossible(HeightTreeNode node)
{
Debug.Assert(node != null);
if (_inRemoval) {
_nodesToCheckForMerging.Add(node);
return;
}
// now check if we need to merge collapsedSections together
var merged = false;
var collapsedL = node.LineNode.CollapsedSections;
if (collapsedL != null) {
for (var i = collapsedL.Count - 1; i >= 0; i--) {
var cs = collapsedL[i];
if (cs.Start == node.DocumentLine || cs.End == node.DocumentLine)
continue;
if (node.Left == null
|| (node.Left.CollapsedSections != null && node.Left.CollapsedSections.Contains(cs)))
{
if (node.Right == null
|| (node.Right.CollapsedSections != null && node.Right.CollapsedSections.Contains(cs)))
{
// all children of node contain cs: -> merge!
if (node.Left != null) node.Left.RemoveDirectlyCollapsed(cs);
if (node.Right != null) node.Right.RemoveDirectlyCollapsed(cs);
collapsedL.RemoveAt(i);
node.AddDirectlyCollapsed(cs);
merged = true;
}
}
}
if (collapsedL.Count == 0)
node.LineNode.CollapsedSections = null;
}
if (merged && node.Parent != null) {
MergeCollapsedSectionsIfPossible(node.Parent);
}
}
#endregion
#region GetNodeBy... / Get...FromNode
private HeightTreeNode GetNodeByIndex(int index)
{
Debug.Assert(index >= 0);
Debug.Assert(index < _root.TotalCount);
var node = _root;
while (true) {
if (node.Left != null && index < node.Left.TotalCount) {
node = node.Left;
} else {
if (node.Left != null) {
index -= node.Left.TotalCount;
}
if (index == 0)
return node;
index--;
node = node.Right;
}
}
}
private HeightTreeNode GetNodeByVisualPosition(double position)
{
var node = _root;
while (true) {
var positionAfterLeft = position;
if (node.Left != null) {
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0) {
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0) {
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0) {
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
} else {
// Descend into right
position = positionBeforeRight;
node = node.Right;
}
}
}
private static double GetVisualPositionFromNode(HeightTreeNode node)
{
var position = (node.Left != null) ? node.Left.TotalHeight : 0;
while (node.Parent != null) {
if (node.IsDirectlyCollapsed)
position = 0;
if (node == node.Parent.Right) {
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
if (positionAfterLeft < 0)
{
// Descend into left
node = node.Left;
continue;
}
}
var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
if (positionBeforeRight < 0)
{
// Found the correct node
return node;
}
if (node.Right == null || node.Right.TotalHeight == 0)
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
if (node.LineNode.TotalHeight > 0 || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
{
return GetNode(line).LineNode.Height;
}
public void SetHeight(DocumentLine line, double val)
{
var node = GetNode(line);
node.LineNode.Height = val;
UpdateAfterChildrenChange(node);
}
public bool GetIsCollapsed(int lineNumber)
{
var node = GetNodeByIndex(lineNumber - 1);
return node.LineNode.IsDirectlyCollapsed || GetIsCollapedFromNode(node);
}
/// <summary>
/// Collapses the specified text section.
/// Runtime: O(log n)
/// </summary>
public CollapsedLineSection CollapseText(DocumentLine start, DocumentLine end)
{
if (!_document.Lines.Contains(start))
throw new ArgumentException("Line is not part of this document", nameof(start));
if (!_document.Lines.Contains(end))
throw new ArgumentException("Line is not part of this document", nameof(end));
var length = end.LineNumber - start.LineNumber + 1;
if (length < 0)
throw new ArgumentException("start must be a line before end");
var section = new CollapsedLineSection(this, start, end);
AddCollapsedSection(section, length);
#if DEBUG
CheckProperties();
#endif
return section;
}
#endregion
#region LineCount & TotalHeight
public int LineCount {
get {
return _root.TotalCount;
}
}
public double TotalHeight {
get {
return _root.TotalHeight;
}
}
#endregion
#region GetAllCollapsedSections
private IEnumerable<HeightTreeNode> AllNodes {
get {
if (_root != null) {
var node = _root.LeftMost;
while (node != null) {
yield return node;
node = node.Successor;
}
}
}
}
internal IEnumerable<CollapsedLineSection> GetAllCollapsedSections()
{
var emptyCsList = new List<CollapsedLineSection>();
return System.Linq.Enumerable.Distinct(
System.Linq.Enumerable.SelectMany(
AllNodes, node => System.Linq.Enumerable.Concat(node.LineNode.CollapsedSections ?? emptyCsList,
node.CollapsedSections ?? emptyCsList)
));
}
#endregion
#region CheckProperties
#if DEBUG
[Conditional("DATACONSISTENCYTEST")]
internal void CheckProperties()
{
CheckProperties(_root);
foreach (var cs in GetAllCollapsedSections()) {
Debug.Assert(GetNode(cs.Start).LineNode.CollapsedSections.Contains(cs));
Debug.Assert(GetNode(cs.End).LineNode.CollapsedSections.Contains(cs));
var endLine = cs.End.LineNumber;
for (var i = cs.Start.LineNumber; i <= endLine; i++) {
CheckIsInSection(cs, GetLineByNumber(i));
}
}
// check red-black property:
var blackCount = -1;
CheckNodeProperties(_root, null, Red, 0, ref blackCount);
}
private void CheckIsInSection(CollapsedLineSection cs, DocumentLine line)
{
var node = GetNode(line);
if (node.LineNode.CollapsedSections != null && node.LineNode.CollapsedSections.Contains(cs))
return;
while (node != null) {
if (node.CollapsedSections != null && node.CollapsedSections.Contains(cs))
return;
node = node.Parent;
}
throw new InvalidOperationException(cs + " not found for line " + line);
}
private void CheckProperties(HeightTreeNode node)
{
var totalCount = 1;
var totalHeight = node.LineNode.TotalHeight;
if (node.LineNode.IsDirectlyCollapsed)
Debug.Assert(node.LineNode.CollapsedSections.Count > 0);
if (node.Left != null) {
CheckProperties(node.Left);
totalCount += node.Left.TotalCount;
totalHeight += node.Left.TotalHeight;
CheckAllContainedIn(node.Left.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Right != null) {
CheckProperties(node.Right);
totalCount += node.Right.TotalCount;
totalHeight += node.Right.TotalHeight;
CheckAllContainedIn(node.Right.CollapsedSections, node.LineNode.CollapsedSections);
}
if (node.Left != null && node.Right != null) {
if (node.Left.CollapsedSections != null && node.Right.CollapsedSections != null) {
var intersection = System.Linq.Enumerable.Intersect(node.Left.CollapsedSections, node.Right.CollapsedSections);
Debug.Assert(System.Linq.Enumerable.Count(intersection) == 0);
}
}
if (node.IsDirectlyCollapsed) {
Debug.Assert(node.CollapsedSections.Count > 0);
totalHeight = 0;
}
Debug.Assert(node.TotalCount == totalCount);
Debug.Assert(node.TotalHeight.IsClose(totalHeight));
}
/// <summary>
/// Checks that all elements in list1 are contained in list2.
/// </summary>
private static void CheckAllContainedIn(IEnumerable<CollapsedLineSection> list1, ICollection<CollapsedLineSection> list2)
{
if (list1 == null) list1 = new List<CollapsedLineSection>();
if (list2 == null) list2 = new List<CollapsedLineSection>();
foreach (var cs in list1) {
Debug.Assert(list2.Contains(cs));
}
}
/*
1. A node is either red or black.
2. The root is black.
3. All leaves are black. (The leaves are the NIL children.)
4. Both children of every red node are black. (So every red node must have a black parent.)
5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
*/
private void CheckNodeProperties(HeightTreeNode node, HeightTreeNode parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
{
if (node == null) return;
Debug.Assert(node.Parent == parentNode);
if (parentColor == Red) {
Debug.Assert(node.Color == Black);
}
if (node.Color == Black) {
blackCount++;
}
if (node.Left == null && node.Right == null) {
// node is a leaf node:
if (expectedBlackCount == -1)
expectedBlackCount = blackCount;
else
Debug.Assert(expectedBlackCount == blackCount);
}
CheckNodeProperties(node.Left, node, node.Color, blackCount, ref expectedBlackCount);
CheckNodeProperties(node.Right, node, node.Color, blackCount, ref expectedBlackCount);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public string GetTreeAsString()
{
var b = new StringBuilder();
AppendTreeToString(_root, b, 0);
return b.ToString();
}
private static void AppendTreeToString(HeightTreeNode node, StringBuilder b, int indent)
{
if (node.Color == Red)
b.Append("RED ");
else
b.Append("BLACK ");
b.AppendLine(node.ToString());
indent += 2;
if (node.Left != null) {
b.Append(' ', indent);
b.Append("L: ");
AppendTreeToString(node.Left, b, indent);
}
if (node.Right != null) {
b.Append(' ', indent);
b.Append("R: ");
AppendTreeToString(node.Right, b, indent);
}
}
#endif
#endregion
#region Red/Black Tree
private const bool Red = true;
private const bool Black = false;
private void InsertAsLeft(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Left == null);
parentNode.Left = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void InsertAsRight(HeightTreeNode parentNode, HeightTreeNode newNode)
{
Debug.Assert(parentNode.Right == null);
parentNode.Right = newNode;
newNode.Parent = parentNode;
newNode.Color = Red;
UpdateAfterChildrenChange(parentNode);
FixTreeOnInsert(newNode);
}
private void FixTreeOnInsert(HeightTreeNode node)
{
Debug.Assert(node != null);
Debug.Assert(node.Color == Red);
Debug.Assert(node.Left == null || node.Left.Color == Black);
Debug.Assert(node.Right == null || node.Right.Color == Black);
var parentNode = node.Parent;
if (parentNode == null) {
// we inserted in the root -> the node must be black
// since this is a root node, making the node black increments the number of black nodes
// on all paths by one, so it is still the same for all paths.
node.Color = Black;
return;
}
if (parentNode.Color == Black) {
// if the parent node where we inserted was black, our red node is placed correctly.
// since we inserted a red node, the number of black nodes on each path is unchanged
// -> the tree is still balanced
return;
}
// parentNode is red, so there is a conflict here!
// because the root is black, parentNode is not the root -> there is a grandparent node
var grandparentNode = parentNode.Parent;
var uncleNode = Sibling(parentNode);
if (uncleNode != null && uncleNode.Color == Red) {
parentNode.Color = Black;
uncleNode.Color = Black;
grandparentNode.Color = Red;
FixTreeOnInsert(grandparentNode);
return;
}
// now we know: parent is red but uncle is black
// First rotation:
if (node == parentNode.Right && parentNode == grandparentNode.Left) {
RotateLeft(parentNode);
node = node.Left;
} else if (node == parentNode.Left && parentNode == grandparentNode.Right) {
RotateRight(parentNode);
node = node.Right;
}
// because node might have changed, reassign variables:
parentNode = node.Parent;
grandparentNode = parentNode.Parent;
// Now recolor a bit:
parentNode.Color = Black;
grandparentNode.Color = Red;
// Second rotation:
if (node == parentNode.Left && parentNode == grandparentNode.Left) {
RotateRight(grandparentNode);
} else {
// because of the first rotation, this is guaranteed:
Debug.Assert(node == parentNode.Right && parentNode == grandparentNode.Right);
RotateLeft(grandparentNode);
}
}
private void RemoveNode(HeightTreeNode removedNode)
{
if (removedNode.Left != null && removedNode.Right != null) {
// replace removedNode with it's in-order successor
var leftMost = removedNode.Right.LeftMost;
var parentOfLeftMost = leftMost.Parent;
RemoveNode(leftMost); // remove leftMost from its current location
BeforeNodeReplace(removedNode, leftMost, parentOfLeftMost);
// and overwrite the removedNode with it
ReplaceNode(removedNode, leftMost);
leftMost.Left = removedNode.Left;
if (leftMost.Left != null) leftMost.Left.Parent = leftMost;
leftMost.Right = removedNode.Right;
if (leftMost.Right != null) leftMost.Right.Parent = leftMost;
leftMost.Color = removedNode.Color;
UpdateAfterChildrenChange(leftMost);
if (leftMost.Parent != null) UpdateAfterChildrenChange(leftMost.Parent);
return;
}
// now either removedNode.left or removedNode.right is null
// get the remaining child
var parentNode = removedNode.Parent;
var childNode = removedNode.Left ?? removedNode.Right;
BeforeNodeRemove(removedNode);
ReplaceNode(removedNode, childNode);
if (parentNode != null) UpdateAfterChildrenChange(parentNode);
if (removedNode.Color == Black) {
if (childNode != null && childNode.Color == Red) {
childNode.Color = Black;
} else {
FixTreeOnDelete(childNode, parentNode);
}
}
}
private void FixTreeOnDelete(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (parentNode == null)
return;
// warning: node may be null
var sibling = Sibling(node, parentNode);
if (sibling.Color == Red) {
parentNode.Color = Red;
sibling.Color = Black;
if (node == parentNode.Left) {
RotateLeft(parentNode);
} else {
RotateRight(parentNode);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
}
if (parentNode.Color == Black
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
FixTreeOnDelete(parentNode, parentNode.Parent);
return;
}
if (parentNode.Color == Red
&& sibling.Color == Black
&& GetColor(sibling.Left) == Black
&& GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
parentNode.Color = Black;
return;
}
if (node == parentNode.Left &&
sibling.Color == Black &&
GetColor(sibling.Left) == Red &&
GetColor(sibling.Right) == Black)
{
sibling.Color = Red;
sibling.Left.Color = Black;
RotateRight(sibling);
}
else if (node == parentNode.Right &&
sibling.Color == Black &&
GetColor(sibling.Right) == Red &&
GetColor(sibling.Left) == Black)
{
sibling.Color = Red;
sibling.Right.Color = Black;
RotateLeft(sibling);
}
sibling = Sibling(node, parentNode); // update value of sibling after rotation
sibling.Color = parentNode.Color;
parentNode.Color = Black;
if (node == parentNode.Left) {
if (sibling.Right != null) {
Debug.Assert(sibling.Right.Color == Red);
sibling.Right.Color = Black;
}
RotateLeft(parentNode);
} else {
if (sibling.Left != null) {
Debug.Assert(sibling.Left.Color == Red);
sibling.Left.Color = Black;
}
RotateRight(parentNode);
}
}
private void ReplaceNode(HeightTreeNode replacedNode, HeightTreeNode newNode)
{
if (replacedNode.Parent == null) {
Debug.Assert(replacedNode == _root);
_root = newNode;
} else {
if (replacedNode.Parent.Left == replacedNode)
replacedNode.Parent.Left = newNode;
else
replacedNode.Parent.Right = newNode;
}
if (newNode != null) {
newNode.Parent = replacedNode.Parent;
}
replacedNode.Parent = null;
}
private void RotateLeft(HeightTreeNode p)
{
// let q be p's right child
var q = p.Right;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's right child to be q's left child
p.Right = q.Left;
if (p.Right != null) p.Right.Parent = p;
// set q's left child to be p
q.Left = p;
p.Parent = q;
UpdateAfterRotateLeft(p);
}
private void RotateRight(HeightTreeNode p)
{
// let q be p's left child
var q = p.Left;
Debug.Assert(q != null);
Debug.Assert(q.Parent == p);
// set q to be the new root
ReplaceNode(p, q);
// set p's left child to be q's right child
p.Left = q.Right;
if (p.Left != null) p.Left.Parent = p;
// set q's right child to be p
q.Right = p;
p.Parent = q;
UpdateAfterRotateRight(p);
}
private static HeightTreeNode Sibling(HeightTreeNode node)
{
if (node == node.Parent.Left)
return node.Parent.Right;
else
return node.Parent.Left;
}
private static HeightTreeNode Sibling(HeightTreeNode node, HeightTreeNode parentNode)
{
Debug.Assert(node == null || node.Parent == parentNode);
if (node == parentNode.Left)
return parentNode.Right;
else
return parentNode.Left;
}
private static bool GetColor(HeightTreeNode node)
{
return node != null ? node.Color : Black;
}
#endregion
#region Collapsing support
private static bool GetIsCollapedFromNode(HeightTreeNode node)
{
while (node != null) {
if (node.IsDirectlyCollapsed)
return true;
node = node.Parent;
}
return false;
}
internal void AddCollapsedSection(CollapsedLineSection section, int sectionLength)
{
AddRemoveCollapsedSection(section, sectionLength, true);
}
private void AddRemoveCollapsedSection(CollapsedLineSection section, int sectionLength, bool add)
{
Debug.Assert(sectionLength > 0);
var node = GetNode(section.Start);
// Go up in the tree.
while (true) {
// Mark all middle nodes as collapsed
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// we are done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// Mark all right subtrees as collapsed.
if (node.Right != null) {
if (node.Right.TotalCount < sectionLength) {
if (add)
node.Right.AddDirectlyCollapsed(section);
else
node.Right.RemoveDirectlyCollapsed(section);
sectionLength -= node.Right.TotalCount;
} else {
// mark partially into the right subtree: go down the right subtree.
AddRemoveCollapsedSectionDown(section, node.Right, sectionLength, add);
break;
}
}
// go up to the next node
var parentNode = node.Parent;
Debug.Assert(parentNode != null);
while (parentNode.Right == node) {
node = parentNode;
parentNode = node.Parent;
Debug.Assert(parentNode != null);
}
node = parentNode;
}
UpdateAugmentedData(GetNode(section.Start), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
UpdateAugmentedData(GetNode(section.End), UpdateAfterChildrenChangeRecursionMode.WholeBranch);
}
private static void AddRemoveCollapsedSectionDown(CollapsedLineSection section, HeightTreeNode node, int sectionLength, bool add)
{
while (true) {
if (node.Left != null) {
if (node.Left.TotalCount < sectionLength) {
// mark left subtree
if (add)
node.Left.AddDirectlyCollapsed(section);
else
node.Left.RemoveDirectlyCollapsed(section);
sectionLength -= node.Left.TotalCount;
} else {
// mark only inside the left subtree
node = node.Left;
Debug.Assert(node != null);
continue;
}
}
if (add)
node.LineNode.AddDirectlyCollapsed(section);
else
node.LineNode.RemoveDirectlyCollapsed(section);
sectionLength -= 1;
if (sectionLength == 0) {
// done!
Debug.Assert(node.DocumentLine == section.End);
break;
}
// mark inside right subtree:
node = node.Right;
Debug.Assert(node != null);
}
}
public void Uncollapse(CollapsedLineSection section)
{
var sectionLength = section.End.LineNumber - section.Start.LineNumber + 1;
AddRemoveCollapsedSection(section, sectionLength, false);
// do not call CheckProperties() in here - Uncollapse is also called during line removals
}
#endregion
}
}
<MSG> Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines
fix rounding errors when building visualtree.
<DFF> @@ -22,6 +22,7 @@ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
+using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
@@ -495,27 +496,27 @@ namespace AvaloniaEdit.Rendering
if (node.Left != null)
{
positionAfterLeft -= node.Left.TotalHeight;
- if (positionAfterLeft < 0)
+ if (MathUtilities.LessThan(positionAfterLeft, 0))
{
// Descend into left
node = node.Left;
continue;
}
}
- var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
- if (positionBeforeRight < 0)
+ var positionBeforeRight = positionAfterLeft - node.LineNode.TotalHeight;
+ if (MathUtilities.LessThan(positionBeforeRight, 0))
{
// Found the correct node
return node;
}
- if (node.Right == null || node.Right.TotalHeight == 0)
+ if (node.Right == null || MathUtilities.IsZero(node.Right.TotalHeight))
{
// Can happen when position>node.totalHeight,
// i.e. at the end of the document, or due to rounding errors in previous loop iterations.
// If node.lineNode isn't collapsed, return that.
// Also return node.lineNode if there is no previous node that we could return instead.
- if (node.LineNode.TotalHeight > 0 || node.Left == null)
+ if (MathUtilities.GreaterThan(node.LineNode.TotalHeight, 0) || node.Left == null)
return node;
// Otherwise, descend into left (find the last non-collapsed node)
node = node.Left;
| 6 | Merge pull request #136 from AvaloniaUI/fixes/rounding-errors-building-visual-lines | 5 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059929 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
static EditingCommandHandler()
{
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> make delete key work on avalonia.
<DFF> @@ -65,7 +65,8 @@ namespace AvaloniaEdit.Editing
static EditingCommandHandler()
{
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
+ // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
+ AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
@@ -329,11 +330,10 @@ namespace AvaloniaEdit.Editing
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
- // HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- args.CanExecute = !textArea.Selection.IsEmpty;
+ args.CanExecute = true;
args.Handled = true;
}
}
| 3 | make delete key work on avalonia. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059930 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
static EditingCommandHandler()
{
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> make delete key work on avalonia.
<DFF> @@ -65,7 +65,8 @@ namespace AvaloniaEdit.Editing
static EditingCommandHandler()
{
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
+ // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
+ AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
@@ -329,11 +330,10 @@ namespace AvaloniaEdit.Editing
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
- // HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- args.CanExecute = !textArea.Selection.IsEmpty;
+ args.CanExecute = true;
args.Handled = true;
}
}
| 3 | make delete key work on avalonia. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059931 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
static EditingCommandHandler()
{
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> make delete key work on avalonia.
<DFF> @@ -65,7 +65,8 @@ namespace AvaloniaEdit.Editing
static EditingCommandHandler()
{
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
+ // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
+ AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
@@ -329,11 +330,10 @@ namespace AvaloniaEdit.Editing
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
- // HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- args.CanExecute = !textArea.Selection.IsEmpty;
+ args.CanExecute = true;
args.Handled = true;
}
}
| 3 | make delete key work on avalonia. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059932 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
static EditingCommandHandler()
{
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> make delete key work on avalonia.
<DFF> @@ -65,7 +65,8 @@ namespace AvaloniaEdit.Editing
static EditingCommandHandler()
{
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
+ // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
+ AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
@@ -329,11 +330,10 @@ namespace AvaloniaEdit.Editing
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
- // HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- args.CanExecute = !textArea.Selection.IsEmpty;
+ args.CanExecute = true;
args.Handled = true;
}
}
| 3 | make delete key work on avalonia. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059933 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
static EditingCommandHandler()
{
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> make delete key work on avalonia.
<DFF> @@ -65,7 +65,8 @@ namespace AvaloniaEdit.Editing
static EditingCommandHandler()
{
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
+ // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
+ AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
@@ -329,11 +330,10 @@ namespace AvaloniaEdit.Editing
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
- // HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- args.CanExecute = !textArea.Selection.IsEmpty;
+ args.CanExecute = true;
args.Handled = true;
}
}
| 3 | make delete key work on avalonia. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059934 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
static EditingCommandHandler()
{
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> make delete key work on avalonia.
<DFF> @@ -65,7 +65,8 @@ namespace AvaloniaEdit.Editing
static EditingCommandHandler()
{
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
+ // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
+ AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
@@ -329,11 +330,10 @@ namespace AvaloniaEdit.Editing
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
- // HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- args.CanExecute = !textArea.Selection.IsEmpty;
+ args.CanExecute = true;
args.Handled = true;
}
}
| 3 | make delete key work on avalonia. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059935 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
static EditingCommandHandler()
{
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> make delete key work on avalonia.
<DFF> @@ -65,7 +65,8 @@ namespace AvaloniaEdit.Editing
static EditingCommandHandler()
{
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
+ // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
+ AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
@@ -329,11 +330,10 @@ namespace AvaloniaEdit.Editing
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
- // HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- args.CanExecute = !textArea.Selection.IsEmpty;
+ args.CanExecute = true;
args.Handled = true;
}
}
| 3 | make delete key work on avalonia. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059936 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
static EditingCommandHandler()
{
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> make delete key work on avalonia.
<DFF> @@ -65,7 +65,8 @@ namespace AvaloniaEdit.Editing
static EditingCommandHandler()
{
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
+ // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
+ AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
@@ -329,11 +330,10 @@ namespace AvaloniaEdit.Editing
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
- // HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- args.CanExecute = !textArea.Selection.IsEmpty;
+ args.CanExecute = true;
args.Handled = true;
}
}
| 3 | make delete key work on avalonia. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059937 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
static EditingCommandHandler()
{
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> make delete key work on avalonia.
<DFF> @@ -65,7 +65,8 @@ namespace AvaloniaEdit.Editing
static EditingCommandHandler()
{
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
+ // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
+ AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
@@ -329,11 +330,10 @@ namespace AvaloniaEdit.Editing
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
- // HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- args.CanExecute = !textArea.Selection.IsEmpty;
+ args.CanExecute = true;
args.Handled = true;
}
}
| 3 | make delete key work on avalonia. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059938 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
static EditingCommandHandler()
{
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> make delete key work on avalonia.
<DFF> @@ -65,7 +65,8 @@ namespace AvaloniaEdit.Editing
static EditingCommandHandler()
{
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
+ // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
+ AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
@@ -329,11 +330,10 @@ namespace AvaloniaEdit.Editing
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
- // HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- args.CanExecute = !textArea.Selection.IsEmpty;
+ args.CanExecute = true;
args.Handled = true;
}
}
| 3 | make delete key work on avalonia. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059939 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
static EditingCommandHandler()
{
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> make delete key work on avalonia.
<DFF> @@ -65,7 +65,8 @@ namespace AvaloniaEdit.Editing
static EditingCommandHandler()
{
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
+ // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
+ AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
@@ -329,11 +330,10 @@ namespace AvaloniaEdit.Editing
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
- // HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- args.CanExecute = !textArea.Selection.IsEmpty;
+ args.CanExecute = true;
args.Handled = true;
}
}
| 3 | make delete key work on avalonia. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059940 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
static EditingCommandHandler()
{
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> make delete key work on avalonia.
<DFF> @@ -65,7 +65,8 @@ namespace AvaloniaEdit.Editing
static EditingCommandHandler()
{
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
+ // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
+ AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
@@ -329,11 +330,10 @@ namespace AvaloniaEdit.Editing
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
- // HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- args.CanExecute = !textArea.Selection.IsEmpty;
+ args.CanExecute = true;
args.Handled = true;
}
}
| 3 | make delete key work on avalonia. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059941 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
static EditingCommandHandler()
{
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> make delete key work on avalonia.
<DFF> @@ -65,7 +65,8 @@ namespace AvaloniaEdit.Editing
static EditingCommandHandler()
{
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
+ // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
+ AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
@@ -329,11 +330,10 @@ namespace AvaloniaEdit.Editing
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
- // HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- args.CanExecute = !textArea.Selection.IsEmpty;
+ args.CanExecute = true;
args.Handled = true;
}
}
| 3 | make delete key work on avalonia. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059942 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
static EditingCommandHandler()
{
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> make delete key work on avalonia.
<DFF> @@ -65,7 +65,8 @@ namespace AvaloniaEdit.Editing
static EditingCommandHandler()
{
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
+ // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
+ AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
@@ -329,11 +330,10 @@ namespace AvaloniaEdit.Editing
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
- // HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- args.CanExecute = !textArea.Selection.IsEmpty;
+ args.CanExecute = true;
args.Handled = true;
}
}
| 3 | make delete key work on avalonia. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059943 | <NME> EditingCommandHandler.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Globalization;
using System.Linq;
using Avalonia;
using AvaloniaEdit.Document;
using Avalonia.Input;
using AvaloniaEdit.Utils;
using System.Threading.Tasks;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// We re-use the CommandBinding and InputBinding instances between multiple text areas,
/// so this class is static.
/// </summary>
internal class EditingCommandHandler
{
/// <summary>
/// Creates a new <see cref="TextAreaInputHandler"/> for the text area.
/// </summary>
public static TextAreaInputHandler Create(TextArea textArea)
{
var handler = new TextAreaInputHandler(textArea);
handler.CommandBindings.AddRange(CommandBindings);
handler.KeyBindings.AddRange(KeyBindings);
return handler;
}
private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>();
private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>();
private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key,
EventHandler<ExecutedRoutedEventArgs> handler)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler));
KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key));
}
private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null)
{
CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler));
}
static EditingCommandHandler()
{
static EditingCommandHandler()
{
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
OnDelete(CaretMovementType.WordLeft));
AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter);
AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter);
AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab);
AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab);
AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy);
AddBinding(ApplicationCommands.Cut, OnCut, CanCut);
AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste);
AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike);
AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine);
AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace);
AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace);
AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase);
AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase);
AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase);
AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase);
AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs);
AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces);
AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs);
AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection);
}
private static TextArea GetTextArea(object target)
{
return target as TextArea;
}
#region Text Transformation Helpers
private enum DefaultSegmentType
{
WholeDocument,
CurrentLine
}
/// <summary>
/// Calls transformLine on all lines in the selected range.
/// transformLine needs to handle read-only segments!
/// </summary>
private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
DocumentLine start, end;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line);
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
start = textArea.Document.Lines.First();
end = textArea.Document.Lines.Last();
}
else
{
start = end = null;
}
}
else
{
var segment = textArea.Selection.SurroundingSegment;
start = textArea.Document.GetLineByOffset(segment.Offset);
end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
}
if (start != null)
{
transformLine(textArea, start);
while (start != end)
{
start = start.NextLine;
transformLine(textArea, start);
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
/// <summary>
/// Calls transformLine on all writable segment in the selected range.
/// </summary>
private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target,
ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
IEnumerable<ISegment> segments;
if (textArea.Selection.IsEmpty)
{
if (defaultSegmentType == DefaultSegmentType.CurrentLine)
{
segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) };
}
else if (defaultSegmentType == DefaultSegmentType.WholeDocument)
{
segments = textArea.Document.Lines;
}
else
{
segments = null;
}
}
else
{
segments = textArea.Selection.Segments;
}
if (segments != null)
{
foreach (var segment in segments.Reverse())
{
foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse())
{
transformSegment(textArea, writableSegment);
}
}
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
#endregion
#region EnterLineBreak
private static void OnEnter(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.IsFocused)
{
textArea.PerformTextInput("\n");
args.Handled = true;
}
}
#endregion
#region Tab
private static void OnTab(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
using (textArea.Document.RunUpdate())
{
if (textArea.Selection.IsMultiline)
{
var segment = textArea.Selection.SurroundingSegment;
var start = textArea.Document.GetLineByOffset(segment.Offset);
var end = textArea.Document.GetLineByOffset(segment.EndOffset);
// don't include the last line if no characters on it are selected
if (start != end && end.Offset == segment.EndOffset)
end = end.PreviousLine;
var current = start;
while (true)
{
var offset = current.Offset;
if (textArea.ReadOnlySectionProvider.CanInsert(offset))
textArea.Document.Replace(offset, 0, textArea.Options.IndentationString,
OffsetChangeMappingType.KeepAnchorBeforeInsertion);
if (current == end)
break;
current = current.NextLine;
}
}
else
{
var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column);
textArea.ReplaceSelectionWithText(indentationString);
}
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static void OnShiftTab(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
var offset = line.Offset;
var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset,
textArea.Options.IndentationSize);
if (s.Length > 0)
{
s = textArea.GetDeletableSegments(s).FirstOrDefault();
if (s != null && s.Length > 0)
{
textArea.Document.Remove(s.Offset, s.Length);
}
}
}, target, args, DefaultSegmentType.CurrentLine);
}
#endregion
#region Delete
private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement)
{
return (target, args) =>
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty)
{
var startPos = textArea.Caret.Position;
var enableVirtualSpace = textArea.Options.EnableVirtualSpace;
// When pressing delete; don't move the caret further into virtual space - instead delete the newline
if (caretMovement == CaretMovementType.CharRight)
enableVirtualSpace = false;
var desiredXPos = textArea.Caret.DesiredXPos;
var endPos = CaretNavigationCommandHandler.GetNewCaretPosition(
textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos);
// GetNewCaretPosition may return (0,0) as new position,
// thus we need to validate endPos before using it in the selection.
if (endPos.Line < 1 || endPos.Column < 1)
endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1));
// Don't do anything if the number of lines of a rectangular selection would be changed by the deletion.
if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line)
return;
// Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic
// Reuse the existing selection, so that we continue using the same logic
textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos)
.ReplaceSelectionWithText(string.Empty);
}
else
{
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
};
}
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
#endregion
#region Clipboard commands
private static void CanCut(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly;
args.Handled = true;
}
}
private static void CanCopy(object target, CanExecuteRoutedEventArgs args)
{
// HasSomethingSelected for copy and cut commands
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty;
args.Handled = true;
}
}
private static void OnCopy(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
CopyWholeLine(textArea, currentLine);
}
else
{
CopySelectedText(textArea);
}
args.Handled = true;
}
}
private static void OnCut(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine)
{
var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line);
if (CopyWholeLine(textArea, currentLine))
{
var segmentsToDelete =
textArea.GetDeletableSegments(
new SimpleSegment(currentLine.Offset, currentLine.TotalLength));
for (var i = segmentsToDelete.Length - 1; i >= 0; i--)
{
textArea.Document.Remove(segmentsToDelete[i]);
}
}
}
else
{
if (CopySelectedText(textArea))
textArea.RemoveSelectedText();
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
private static bool CopySelectedText(TextArea textArea)
{
var text = textArea.Selection.GetText();
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void SetClipboardText(string text)
{
try
{
Application.Current.Clipboard.SetTextAsync(text).GetAwaiter().GetResult();
}
catch (Exception)
{
// Apparently this exception sometimes happens randomly.
// The MS controls just ignore it, so we'll do the same.
}
}
private static bool CopyWholeLine(TextArea textArea, DocumentLine line)
{
ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
var text = textArea.Document.GetText(wholeLine);
// Ignore empty line copy
if(string.IsNullOrEmpty(text)) return false;
// Ensure we use the appropriate newline sequence for the OS
text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
// TODO: formats
//DataObject data = new DataObject();
//if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
// data.SetText(text);
//// Also copy text in HTML format to clipboard - good for pasting text into Word
//// or to the SharpDevelop forums.
//if (ConfirmDataFormat(textArea, data, DataFormats.Html))
//{
// IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
// HtmlClipboard.SetHtml(data,
// HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine,
// new HtmlOptions(textArea.Options)));
//}
//if (ConfirmDataFormat(textArea, data, LineSelectedType))
//{
// var lineSelected = new MemoryStream(1);
// lineSelected.WriteByte(1);
// data.SetData(LineSelectedType, lineSelected, false);
//}
//var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
//textArea.RaiseEvent(copyingEventArgs);
//if (copyingEventArgs.CommandCancelled)
// return false;
SetClipboardText(text);
textArea.OnTextCopied(new TextEventArgs(text));
return true;
}
private static void CanPaste(object target, CanExecuteRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset);
args.Handled = true;
}
}
private static async void OnPaste(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
textArea.Document.BeginUpdate();
string text = null;
try
{
text = await Application.Current.Clipboard.GetTextAsync();
}
catch (Exception)
{
textArea.Document.EndUpdate();
return;
}
if (text == null)
return;
text = GetTextToPaste(text, textArea);
if (!string.IsNullOrEmpty(text))
{
textArea.ReplaceSelectionWithText(text);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
textArea.Document.EndUpdate();
}
}
internal static string GetTextToPaste(string text, TextArea textArea)
{
try
{
// Try retrieving the text as one of:
// - the FormatToApply
// - UnicodeText
// - Text
// (but don't try the same format twice)
//if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply))
// text = (string)dataObject.GetData(pastingEventArgs.FormatToApply);
//else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText &&
// dataObject.GetDataPresent(DataFormats.UnicodeText))
// text = (string)dataObject.GetData(DataFormats.UnicodeText);
//else if (pastingEventArgs.FormatToApply != DataFormats.Text &&
// dataObject.GetDataPresent(DataFormats.Text))
// text = (string)dataObject.GetData(DataFormats.Text);
//else
// return null; // no text data format
// convert text back to correct newlines for this document
var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line);
text = TextUtilities.NormalizeNewLines(text, newLine);
text = textArea.Options.ConvertTabsToSpaces
? text.Replace("\t", new String(' ', textArea.Options.IndentationSize))
: text;
return text;
}
catch (OutOfMemoryException)
{
// may happen when trying to paste a huge string
return null;
}
}
#endregion
#region Toggle Overstrike
private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea != null && textArea.Options.AllowToggleOverstrikeMode)
textArea.OverstrikeMode = !textArea.OverstrikeMode;
}
#endregion
#region DeleteLine
private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
int firstLineIndex, lastLineIndex;
if (textArea.Selection.Length == 0)
{
// There is no selection, simply delete current line
firstLineIndex = lastLineIndex = textArea.Caret.Line;
}
else
{
// There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction)
firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line,
textArea.Selection.EndPosition.Line);
}
var startLine = textArea.Document.GetLineByNumber(firstLineIndex);
var endLine = textArea.Document.GetLineByNumber(lastLineIndex);
textArea.Selection = Selection.Create(textArea, startLine.Offset,
endLine.Offset + endLine.TotalLength);
textArea.RemoveSelectedText();
args.Handled = true;
}
}
#endregion
#region Remove..Whitespace / Convert Tabs-Spaces
private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationString = new string(' ', textArea.Options.IndentationSize);
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == '\t')
{
document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace);
endOffset += indentationString.Length - 1;
}
}
}
private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args)
{
TransformSelectedLines(
delegate (TextArea textArea, DocumentLine line)
{
ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line));
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment)
{
var document = textArea.Document;
var endOffset = segment.EndOffset;
var indentationSize = textArea.Options.IndentationSize;
var spacesCount = 0;
for (var offset = segment.Offset; offset < endOffset; offset++)
{
if (document.GetCharAt(offset) == ' ')
{
spacesCount++;
if (spacesCount == indentationSize)
{
document.Replace(offset - (indentationSize - 1), indentationSize, "\t",
OffsetChangeMappingType.CharacterReplace);
spacesCount = 0;
offset -= indentationSize - 1;
endOffset -= indentationSize - 1;
}
}
else
{
spacesCount = 0;
}
}
}
#endregion
#region Convert...Case
private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment)
{
var oldText = textArea.Document.GetText(segment);
var newText = transformText(oldText);
textArea.Document.Replace(segment.Offset, segment.Length, newText,
OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDocument);
}
private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args);
}
private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args);
}
private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args)
{
throw new NotSupportedException();
//ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args);
}
private static void OnInvertCase(object target, ExecutedRoutedEventArgs args)
{
ConvertCase(InvertCase, target, args);
}
private static string InvertCase(string text)
{
// TODO: culture
//var culture = CultureInfo.CurrentCulture;
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; ++i)
{
var c = buffer[i];
buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
return new string(buffer);
}
#endregion
private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args)
{
var textArea = GetTextArea(target);
if (textArea?.Document != null && textArea.IndentationStrategy != null)
{
using (textArea.Document.RunUpdate())
{
int start, end;
if (textArea.Selection.IsEmpty)
{
start = 1;
end = textArea.Document.LineCount;
}
else
{
start = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.Offset)
.LineNumber;
end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset)
.LineNumber;
}
textArea.IndentationStrategy.IndentLines(textArea.Document, start, end);
}
textArea.Caret.BringCaretToView();
args.Handled = true;
}
}
}
}
<MSG> make delete key work on avalonia.
<DFF> @@ -65,7 +65,8 @@ namespace AvaloniaEdit.Editing
static EditingCommandHandler()
{
- AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete);
+ // TODO ApplicationCommands.Delete gets called, but never editing commands.Delete (since porting to avalonia.)
+ AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.CharRight), CanDelete);
AddBinding(EditingCommands.Delete, InputModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight));
AddBinding(EditingCommands.DeleteNextWord, InputModifiers.Control, Key.Delete,
OnDelete(CaretMovementType.WordRight));
@@ -329,11 +330,10 @@ namespace AvaloniaEdit.Editing
private static void CanDelete(object target, CanExecuteRoutedEventArgs args)
{
- // HasSomethingSelected for delete command
var textArea = GetTextArea(target);
if (textArea?.Document != null)
{
- args.CanExecute = !textArea.Selection.IsEmpty;
+ args.CanExecute = true;
args.Handled = true;
}
}
| 3 | make delete key work on avalonia. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059944 | <NME> define.js
<BEF>
/*jslint browser:true, node:true, laxbreak:true*/
'use strict';
module.exports = function(fm) {
/**
* Defines a module.
*
* Options:
*
* - `name {String}` the name of the module
* - `tag {String}` the tagName to use for the root element
* - `classes {Array}` a list of classes to add to the root element
* - `template {Function}` the template function to use when rendering
* - `helpers {Array}` a lsit of helpers to apply to the module
* - `initialize {Function}` custom logic to run when module instance created
* - `setup {Function}` custom logic to run when `.setup()` is called (directly or indirectly)
* - `teardown {Function}` custom logic to unbind/undo anything setup introduced (called on `.destroy()` and sometimes on `.setup()` to avoid double binding events)
* - `destroy {Function}` logic to permanently destroy all references
*
* @param {Object|View} props
* @return {View}
* @public true
*/
return function(props) {
var Module = ('object' === typeof props)
? fm.Module.extend(props)
: props;
// Allow modules to be named
// via 'name:' or 'module:'
var proto = Module.prototype;
var name = proto.name || proto._module;
// Store the module by module type
// so that module can be referred to
// by just a string in layout definitions
if (name) fm.modules[name] = Module;
return Module;
};
};
<MSG> Fix bunch of typos
<DFF> @@ -14,7 +14,7 @@ module.exports = function(fm) {
* - `tag {String}` the tagName to use for the root element
* - `classes {Array}` a list of classes to add to the root element
* - `template {Function}` the template function to use when rendering
- * - `helpers {Array}` a lsit of helpers to apply to the module
+ * - `helpers {Array}` a list of helpers to apply to the module
* - `initialize {Function}` custom logic to run when module instance created
* - `setup {Function}` custom logic to run when `.setup()` is called (directly or indirectly)
* - `teardown {Function}` custom logic to unbind/undo anything setup introduced (called on `.destroy()` and sometimes on `.setup()` to avoid double binding events)
| 1 | Fix bunch of typos | 1 | .js | js | mit | ftlabs/fruitmachine |
10059945 | <NME> SingleCharacterElementGenerator.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.CodeAnalysis;
using Avalonia;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
// This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions.
/// <summary>
/// Element generator that displays · for spaces and » for tabs and a box for control characters.
/// </summary>
/// <remarks>
/// This element generator is present in every TextView by default; the enabled features can be configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")]
internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator
{
/// <summary>
/// Gets/Sets whether to show · for spaces.
/// </summary>
public bool ShowSpaces { get; set; }
/// <summary>
/// Gets/Sets whether to show » for tabs.
/// </summary>
public bool ShowTabs { get; set; }
/// <summary>
/// Gets/Sets whether to show a box with the hex code for control characters.
/// </summary>
public bool ShowBoxForControlCharacters { get; set; }
/// <summary>
/// Creates a new SingleCharacterElementGenerator instance.
/// </summary>
public SingleCharacterElementGenerator()
{
ShowSpaces = true;
ShowTabs = true;
ShowBoxForControlCharacters = true;
}
void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options)
{
ShowSpaces = options.ShowSpaces;
ShowTabs = options.ShowTabs;
ShowBoxForControlCharacters = options.ShowBoxForControlCharacters;
}
public override int GetFirstInterestedOffset(int startOffset)
{
var endLine = CurrentContext.VisualLine.LastDocumentLine;
var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset);
for (var i = 0; i < relevantText.Count; i++) {
var c = relevantText.Text[relevantText.Offset + i];
switch (c) {
case ' ':
if (ShowSpaces)
return startOffset + i;
break;
case '\t':
if (ShowTabs)
return startOffset + i;
break;
default:
if (ShowBoxForControlCharacters && char.IsControl(c)) {
return startOffset + i;
}
break;
}
}
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
var c = CurrentContext.Document.GetCharAt(offset);
if (ShowSpaces && c == ' ')
{
var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties);
runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush);
return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter(
CurrentContext.TextView.Options.ShowSpacesGlyph,
runProperties));
}
else if (ShowTabs && c == '\t')
{
var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties);
runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush);
return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter(
CurrentContext.TextView.Options.ShowTabsGlyph,
runProperties));
}
else if (ShowBoxForControlCharacters && char.IsControl(c))
{
var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties);
runProperties.SetForegroundBrush(Brushes.White);
var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView);
var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties);
return new SpecialCharacterBoxElement(text);
}
return null;
}
private sealed class SpaceTextElement : FormattedTextElement
{
public SpaceTextElement(TextLine textLine) : base(textLine, 1)
{
}
public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode)
{
if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint)
return base.GetNextCaretPosition(visualColumn, direction, mode);
else
return -1;
}
public override bool IsWhitespace(int visualColumn)
{
return true;
}
}
private sealed class TabTextElement : VisualLineElement
{
internal readonly TextLine Text;
public TabTextElement(TextLine text) : base(2, 1)
{
Text = text;
}
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
// the TabTextElement consists of two TextRuns:
// first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation
if (startVisualColumn == VisualColumn)
return new TabGlyphRun(this, TextRunProperties);
else if (startVisualColumn == VisualColumn + 1)
return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties);
else
throw new ArgumentOutOfRangeException(nameof(startVisualColumn));
}
public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode)
{
if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint)
return base.GetNextCaretPosition(visualColumn, direction, mode);
else
return -1;
}
public override bool IsWhitespace(int visualColumn)
{
return true;
}
}
private sealed class TabGlyphRun : DrawableTextRun
{
private readonly TabTextElement _element;
public TabGlyphRun(TabTextElement element, TextRunProperties properties)
{
if (properties == null)
throw new ArgumentNullException(nameof(properties));
Properties = properties;
_element = element;
}
public override TextRunProperties Properties { get; }
public override double Baseline => _element.Text.Baseline;
public override Size Size => Size.Empty;
public override void Draw(DrawingContext drawingContext, Point origin)
{
_element.Text.Draw(drawingContext, origin);
}
}
private sealed class SpecialCharacterBoxElement : FormattedTextElement
{
public SpecialCharacterBoxElement(TextLine text) : base(text, 1)
{
}
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
return new SpecialCharacterTextRun(this, TextRunProperties);
}
}
private sealed class SpecialCharacterTextRun : FormattedTextRun
{
private static readonly ISolidColorBrush DarkGrayBrush;
static SpecialCharacterTextRun()
{
DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128));
}
public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties)
: base(element, properties)
{
}
public override Rect ComputeBoundingBox()
{
var r = base.ComputeBoundingBox();
return r.WithWidth(r.Width + 3);
}
public override void Draw(DrawingContext drawingContext, Point origin)
{
var newOrigin = new Point(origin.X + 1.5, origin.Y);
var metrics = GetSize(double.PositiveInfinity);
var r = new Rect(newOrigin.X - 0.5, newOrigin.Y, metrics.Width + 2, metrics.Height);
drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f);
base.Draw(drawingContext, newOrigin);
}
var newOrigin = new Point(x + (BoxMargin / 2), y);
var (width, height) = Size;
var r = new Rect(x, y, width, height);
drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f);
base.Draw(drawingContext, newOrigin);
}
}
}
}
<MSG> Fixed margins for the box displayed for ControlCharacters
<DFF> @@ -225,11 +225,12 @@ namespace AvaloniaEdit.Rendering
private sealed class SpecialCharacterTextRun : FormattedTextRun
{
+ private const double _boxMargin = 3;
private static readonly ISolidColorBrush DarkGrayBrush;
static SpecialCharacterTextRun()
{
- DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128));
+ DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128));
}
public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties)
@@ -237,17 +238,17 @@ namespace AvaloniaEdit.Rendering
{
}
- public override Rect ComputeBoundingBox()
+ public override Size GetSize(double remainingParagraphWidth)
{
- var r = base.ComputeBoundingBox();
- return r.WithWidth(r.Width + 3);
+ var s = base.GetSize(remainingParagraphWidth);
+ return s.WithWidth(s.Width + _boxMargin);
}
public override void Draw(DrawingContext drawingContext, Point origin)
{
- var newOrigin = new Point(origin.X + 1.5, origin.Y);
+ var newOrigin = new Point(origin.X + (_boxMargin / 2), origin.Y);
var metrics = GetSize(double.PositiveInfinity);
- var r = new Rect(newOrigin.X - 0.5, newOrigin.Y, metrics.Width + 2, metrics.Height);
+ var r = new Rect(origin.X, origin.Y, metrics.Width, metrics.Height);
drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f);
base.Draw(drawingContext, newOrigin);
}
| 7 | Fixed margins for the box displayed for ControlCharacters | 6 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059946 | <NME> SingleCharacterElementGenerator.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.CodeAnalysis;
using Avalonia;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
// This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions.
/// <summary>
/// Element generator that displays · for spaces and » for tabs and a box for control characters.
/// </summary>
/// <remarks>
/// This element generator is present in every TextView by default; the enabled features can be configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")]
internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator
{
/// <summary>
/// Gets/Sets whether to show · for spaces.
/// </summary>
public bool ShowSpaces { get; set; }
/// <summary>
/// Gets/Sets whether to show » for tabs.
/// </summary>
public bool ShowTabs { get; set; }
/// <summary>
/// Gets/Sets whether to show a box with the hex code for control characters.
/// </summary>
public bool ShowBoxForControlCharacters { get; set; }
/// <summary>
/// Creates a new SingleCharacterElementGenerator instance.
/// </summary>
public SingleCharacterElementGenerator()
{
ShowSpaces = true;
ShowTabs = true;
ShowBoxForControlCharacters = true;
}
void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options)
{
ShowSpaces = options.ShowSpaces;
ShowTabs = options.ShowTabs;
ShowBoxForControlCharacters = options.ShowBoxForControlCharacters;
}
public override int GetFirstInterestedOffset(int startOffset)
{
var endLine = CurrentContext.VisualLine.LastDocumentLine;
var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset);
for (var i = 0; i < relevantText.Count; i++) {
var c = relevantText.Text[relevantText.Offset + i];
switch (c) {
case ' ':
if (ShowSpaces)
return startOffset + i;
break;
case '\t':
if (ShowTabs)
return startOffset + i;
break;
default:
if (ShowBoxForControlCharacters && char.IsControl(c)) {
return startOffset + i;
}
break;
}
}
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
var c = CurrentContext.Document.GetCharAt(offset);
if (ShowSpaces && c == ' ')
{
var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties);
runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush);
return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter(
CurrentContext.TextView.Options.ShowSpacesGlyph,
runProperties));
}
else if (ShowTabs && c == '\t')
{
var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties);
runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush);
return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter(
CurrentContext.TextView.Options.ShowTabsGlyph,
runProperties));
}
else if (ShowBoxForControlCharacters && char.IsControl(c))
{
var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties);
runProperties.SetForegroundBrush(Brushes.White);
var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView);
var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties);
return new SpecialCharacterBoxElement(text);
}
return null;
}
private sealed class SpaceTextElement : FormattedTextElement
{
public SpaceTextElement(TextLine textLine) : base(textLine, 1)
{
}
public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode)
{
if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint)
return base.GetNextCaretPosition(visualColumn, direction, mode);
else
return -1;
}
public override bool IsWhitespace(int visualColumn)
{
return true;
}
}
private sealed class TabTextElement : VisualLineElement
{
internal readonly TextLine Text;
public TabTextElement(TextLine text) : base(2, 1)
{
Text = text;
}
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
// the TabTextElement consists of two TextRuns:
// first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation
if (startVisualColumn == VisualColumn)
return new TabGlyphRun(this, TextRunProperties);
else if (startVisualColumn == VisualColumn + 1)
return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties);
else
throw new ArgumentOutOfRangeException(nameof(startVisualColumn));
}
public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode)
{
if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint)
return base.GetNextCaretPosition(visualColumn, direction, mode);
else
return -1;
}
public override bool IsWhitespace(int visualColumn)
{
return true;
}
}
private sealed class TabGlyphRun : DrawableTextRun
{
private readonly TabTextElement _element;
public TabGlyphRun(TabTextElement element, TextRunProperties properties)
{
if (properties == null)
throw new ArgumentNullException(nameof(properties));
Properties = properties;
_element = element;
}
public override TextRunProperties Properties { get; }
public override double Baseline => _element.Text.Baseline;
public override Size Size => Size.Empty;
public override void Draw(DrawingContext drawingContext, Point origin)
{
_element.Text.Draw(drawingContext, origin);
}
}
private sealed class SpecialCharacterBoxElement : FormattedTextElement
{
public SpecialCharacterBoxElement(TextLine text) : base(text, 1)
{
}
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
return new SpecialCharacterTextRun(this, TextRunProperties);
}
}
private sealed class SpecialCharacterTextRun : FormattedTextRun
{
private static readonly ISolidColorBrush DarkGrayBrush;
static SpecialCharacterTextRun()
{
DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128));
}
public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties)
: base(element, properties)
{
}
public override Rect ComputeBoundingBox()
{
var r = base.ComputeBoundingBox();
return r.WithWidth(r.Width + 3);
}
public override void Draw(DrawingContext drawingContext, Point origin)
{
var newOrigin = new Point(origin.X + 1.5, origin.Y);
var metrics = GetSize(double.PositiveInfinity);
var r = new Rect(newOrigin.X - 0.5, newOrigin.Y, metrics.Width + 2, metrics.Height);
drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f);
base.Draw(drawingContext, newOrigin);
}
var newOrigin = new Point(x + (BoxMargin / 2), y);
var (width, height) = Size;
var r = new Rect(x, y, width, height);
drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f);
base.Draw(drawingContext, newOrigin);
}
}
}
}
<MSG> Fixed margins for the box displayed for ControlCharacters
<DFF> @@ -225,11 +225,12 @@ namespace AvaloniaEdit.Rendering
private sealed class SpecialCharacterTextRun : FormattedTextRun
{
+ private const double _boxMargin = 3;
private static readonly ISolidColorBrush DarkGrayBrush;
static SpecialCharacterTextRun()
{
- DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128));
+ DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128));
}
public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties)
@@ -237,17 +238,17 @@ namespace AvaloniaEdit.Rendering
{
}
- public override Rect ComputeBoundingBox()
+ public override Size GetSize(double remainingParagraphWidth)
{
- var r = base.ComputeBoundingBox();
- return r.WithWidth(r.Width + 3);
+ var s = base.GetSize(remainingParagraphWidth);
+ return s.WithWidth(s.Width + _boxMargin);
}
public override void Draw(DrawingContext drawingContext, Point origin)
{
- var newOrigin = new Point(origin.X + 1.5, origin.Y);
+ var newOrigin = new Point(origin.X + (_boxMargin / 2), origin.Y);
var metrics = GetSize(double.PositiveInfinity);
- var r = new Rect(newOrigin.X - 0.5, newOrigin.Y, metrics.Width + 2, metrics.Height);
+ var r = new Rect(origin.X, origin.Y, metrics.Width, metrics.Height);
drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f);
base.Draw(drawingContext, newOrigin);
}
| 7 | Fixed margins for the box displayed for ControlCharacters | 6 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059947 | <NME> SingleCharacterElementGenerator.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.CodeAnalysis;
using Avalonia;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
// This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions.
/// <summary>
/// Element generator that displays · for spaces and » for tabs and a box for control characters.
/// </summary>
/// <remarks>
/// This element generator is present in every TextView by default; the enabled features can be configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")]
internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator
{
/// <summary>
/// Gets/Sets whether to show · for spaces.
/// </summary>
public bool ShowSpaces { get; set; }
/// <summary>
/// Gets/Sets whether to show » for tabs.
/// </summary>
public bool ShowTabs { get; set; }
/// <summary>
/// Gets/Sets whether to show a box with the hex code for control characters.
/// </summary>
public bool ShowBoxForControlCharacters { get; set; }
/// <summary>
/// Creates a new SingleCharacterElementGenerator instance.
/// </summary>
public SingleCharacterElementGenerator()
{
ShowSpaces = true;
ShowTabs = true;
ShowBoxForControlCharacters = true;
}
void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options)
{
ShowSpaces = options.ShowSpaces;
ShowTabs = options.ShowTabs;
ShowBoxForControlCharacters = options.ShowBoxForControlCharacters;
}
public override int GetFirstInterestedOffset(int startOffset)
{
var endLine = CurrentContext.VisualLine.LastDocumentLine;
var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset);
for (var i = 0; i < relevantText.Count; i++) {
var c = relevantText.Text[relevantText.Offset + i];
switch (c) {
case ' ':
if (ShowSpaces)
return startOffset + i;
break;
case '\t':
if (ShowTabs)
return startOffset + i;
break;
default:
if (ShowBoxForControlCharacters && char.IsControl(c)) {
return startOffset + i;
}
break;
}
}
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
var c = CurrentContext.Document.GetCharAt(offset);
if (ShowSpaces && c == ' ')
{
var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties);
runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush);
return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter(
CurrentContext.TextView.Options.ShowSpacesGlyph,
runProperties));
}
else if (ShowTabs && c == '\t')
{
var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties);
runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush);
return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter(
CurrentContext.TextView.Options.ShowTabsGlyph,
runProperties));
}
else if (ShowBoxForControlCharacters && char.IsControl(c))
{
var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties);
runProperties.SetForegroundBrush(Brushes.White);
var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView);
var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties);
return new SpecialCharacterBoxElement(text);
}
return null;
}
private sealed class SpaceTextElement : FormattedTextElement
{
public SpaceTextElement(TextLine textLine) : base(textLine, 1)
{
}
public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode)
{
if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint)
return base.GetNextCaretPosition(visualColumn, direction, mode);
else
return -1;
}
public override bool IsWhitespace(int visualColumn)
{
return true;
}
}
private sealed class TabTextElement : VisualLineElement
{
internal readonly TextLine Text;
public TabTextElement(TextLine text) : base(2, 1)
{
Text = text;
}
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
// the TabTextElement consists of two TextRuns:
// first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation
if (startVisualColumn == VisualColumn)
return new TabGlyphRun(this, TextRunProperties);
else if (startVisualColumn == VisualColumn + 1)
return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties);
else
throw new ArgumentOutOfRangeException(nameof(startVisualColumn));
}
public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode)
{
if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint)
return base.GetNextCaretPosition(visualColumn, direction, mode);
else
return -1;
}
public override bool IsWhitespace(int visualColumn)
{
return true;
}
}
private sealed class TabGlyphRun : DrawableTextRun
{
private readonly TabTextElement _element;
public TabGlyphRun(TabTextElement element, TextRunProperties properties)
{
if (properties == null)
throw new ArgumentNullException(nameof(properties));
Properties = properties;
_element = element;
}
public override TextRunProperties Properties { get; }
public override double Baseline => _element.Text.Baseline;
public override Size Size => Size.Empty;
public override void Draw(DrawingContext drawingContext, Point origin)
{
_element.Text.Draw(drawingContext, origin);
}
}
private sealed class SpecialCharacterBoxElement : FormattedTextElement
{
public SpecialCharacterBoxElement(TextLine text) : base(text, 1)
{
}
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
return new SpecialCharacterTextRun(this, TextRunProperties);
}
}
private sealed class SpecialCharacterTextRun : FormattedTextRun
{
private static readonly ISolidColorBrush DarkGrayBrush;
static SpecialCharacterTextRun()
{
DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128));
}
public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties)
: base(element, properties)
{
}
public override Rect ComputeBoundingBox()
{
var r = base.ComputeBoundingBox();
return r.WithWidth(r.Width + 3);
}
public override void Draw(DrawingContext drawingContext, Point origin)
{
var newOrigin = new Point(origin.X + 1.5, origin.Y);
var metrics = GetSize(double.PositiveInfinity);
var r = new Rect(newOrigin.X - 0.5, newOrigin.Y, metrics.Width + 2, metrics.Height);
drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f);
base.Draw(drawingContext, newOrigin);
}
var newOrigin = new Point(x + (BoxMargin / 2), y);
var (width, height) = Size;
var r = new Rect(x, y, width, height);
drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f);
base.Draw(drawingContext, newOrigin);
}
}
}
}
<MSG> Fixed margins for the box displayed for ControlCharacters
<DFF> @@ -225,11 +225,12 @@ namespace AvaloniaEdit.Rendering
private sealed class SpecialCharacterTextRun : FormattedTextRun
{
+ private const double _boxMargin = 3;
private static readonly ISolidColorBrush DarkGrayBrush;
static SpecialCharacterTextRun()
{
- DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128));
+ DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128));
}
public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties)
@@ -237,17 +238,17 @@ namespace AvaloniaEdit.Rendering
{
}
- public override Rect ComputeBoundingBox()
+ public override Size GetSize(double remainingParagraphWidth)
{
- var r = base.ComputeBoundingBox();
- return r.WithWidth(r.Width + 3);
+ var s = base.GetSize(remainingParagraphWidth);
+ return s.WithWidth(s.Width + _boxMargin);
}
public override void Draw(DrawingContext drawingContext, Point origin)
{
- var newOrigin = new Point(origin.X + 1.5, origin.Y);
+ var newOrigin = new Point(origin.X + (_boxMargin / 2), origin.Y);
var metrics = GetSize(double.PositiveInfinity);
- var r = new Rect(newOrigin.X - 0.5, newOrigin.Y, metrics.Width + 2, metrics.Height);
+ var r = new Rect(origin.X, origin.Y, metrics.Width, metrics.Height);
drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f);
base.Draw(drawingContext, newOrigin);
}
| 7 | Fixed margins for the box displayed for ControlCharacters | 6 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059948 | <NME> SingleCharacterElementGenerator.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.CodeAnalysis;
using Avalonia;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
// This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions.
/// <summary>
/// Element generator that displays · for spaces and » for tabs and a box for control characters.
/// </summary>
/// <remarks>
/// This element generator is present in every TextView by default; the enabled features can be configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")]
internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator
{
/// <summary>
/// Gets/Sets whether to show · for spaces.
/// </summary>
public bool ShowSpaces { get; set; }
/// <summary>
/// Gets/Sets whether to show » for tabs.
/// </summary>
public bool ShowTabs { get; set; }
/// <summary>
/// Gets/Sets whether to show a box with the hex code for control characters.
/// </summary>
public bool ShowBoxForControlCharacters { get; set; }
/// <summary>
/// Creates a new SingleCharacterElementGenerator instance.
/// </summary>
public SingleCharacterElementGenerator()
{
ShowSpaces = true;
ShowTabs = true;
ShowBoxForControlCharacters = true;
}
void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options)
{
ShowSpaces = options.ShowSpaces;
ShowTabs = options.ShowTabs;
ShowBoxForControlCharacters = options.ShowBoxForControlCharacters;
}
public override int GetFirstInterestedOffset(int startOffset)
{
var endLine = CurrentContext.VisualLine.LastDocumentLine;
var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset);
for (var i = 0; i < relevantText.Count; i++) {
var c = relevantText.Text[relevantText.Offset + i];
switch (c) {
case ' ':
if (ShowSpaces)
return startOffset + i;
break;
case '\t':
if (ShowTabs)
return startOffset + i;
break;
default:
if (ShowBoxForControlCharacters && char.IsControl(c)) {
return startOffset + i;
}
break;
}
}
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
var c = CurrentContext.Document.GetCharAt(offset);
if (ShowSpaces && c == ' ')
{
var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties);
runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush);
return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter(
CurrentContext.TextView.Options.ShowSpacesGlyph,
runProperties));
}
else if (ShowTabs && c == '\t')
{
var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties);
runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush);
return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter(
CurrentContext.TextView.Options.ShowTabsGlyph,
runProperties));
}
else if (ShowBoxForControlCharacters && char.IsControl(c))
{
var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties);
runProperties.SetForegroundBrush(Brushes.White);
var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView);
var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties);
return new SpecialCharacterBoxElement(text);
}
return null;
}
private sealed class SpaceTextElement : FormattedTextElement
{
public SpaceTextElement(TextLine textLine) : base(textLine, 1)
{
}
public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode)
{
if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint)
return base.GetNextCaretPosition(visualColumn, direction, mode);
else
return -1;
}
public override bool IsWhitespace(int visualColumn)
{
return true;
}
}
private sealed class TabTextElement : VisualLineElement
{
internal readonly TextLine Text;
public TabTextElement(TextLine text) : base(2, 1)
{
Text = text;
}
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
// the TabTextElement consists of two TextRuns:
// first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation
if (startVisualColumn == VisualColumn)
return new TabGlyphRun(this, TextRunProperties);
else if (startVisualColumn == VisualColumn + 1)
return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties);
else
throw new ArgumentOutOfRangeException(nameof(startVisualColumn));
}
public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode)
{
if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint)
return base.GetNextCaretPosition(visualColumn, direction, mode);
else
return -1;
}
public override bool IsWhitespace(int visualColumn)
{
return true;
}
}
private sealed class TabGlyphRun : DrawableTextRun
{
private readonly TabTextElement _element;
public TabGlyphRun(TabTextElement element, TextRunProperties properties)
{
if (properties == null)
throw new ArgumentNullException(nameof(properties));
Properties = properties;
_element = element;
}
public override TextRunProperties Properties { get; }
public override double Baseline => _element.Text.Baseline;
public override Size Size => Size.Empty;
public override void Draw(DrawingContext drawingContext, Point origin)
{
_element.Text.Draw(drawingContext, origin);
}
}
private sealed class SpecialCharacterBoxElement : FormattedTextElement
{
public SpecialCharacterBoxElement(TextLine text) : base(text, 1)
{
}
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
return new SpecialCharacterTextRun(this, TextRunProperties);
}
}
private sealed class SpecialCharacterTextRun : FormattedTextRun
{
private static readonly ISolidColorBrush DarkGrayBrush;
static SpecialCharacterTextRun()
{
DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128));
}
public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties)
: base(element, properties)
{
}
public override Rect ComputeBoundingBox()
{
var r = base.ComputeBoundingBox();
return r.WithWidth(r.Width + 3);
}
public override void Draw(DrawingContext drawingContext, Point origin)
{
var newOrigin = new Point(origin.X + 1.5, origin.Y);
var metrics = GetSize(double.PositiveInfinity);
var r = new Rect(newOrigin.X - 0.5, newOrigin.Y, metrics.Width + 2, metrics.Height);
drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f);
base.Draw(drawingContext, newOrigin);
}
var newOrigin = new Point(x + (BoxMargin / 2), y);
var (width, height) = Size;
var r = new Rect(x, y, width, height);
drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f);
base.Draw(drawingContext, newOrigin);
}
}
}
}
<MSG> Fixed margins for the box displayed for ControlCharacters
<DFF> @@ -225,11 +225,12 @@ namespace AvaloniaEdit.Rendering
private sealed class SpecialCharacterTextRun : FormattedTextRun
{
+ private const double _boxMargin = 3;
private static readonly ISolidColorBrush DarkGrayBrush;
static SpecialCharacterTextRun()
{
- DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128));
+ DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128));
}
public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties)
@@ -237,17 +238,17 @@ namespace AvaloniaEdit.Rendering
{
}
- public override Rect ComputeBoundingBox()
+ public override Size GetSize(double remainingParagraphWidth)
{
- var r = base.ComputeBoundingBox();
- return r.WithWidth(r.Width + 3);
+ var s = base.GetSize(remainingParagraphWidth);
+ return s.WithWidth(s.Width + _boxMargin);
}
public override void Draw(DrawingContext drawingContext, Point origin)
{
- var newOrigin = new Point(origin.X + 1.5, origin.Y);
+ var newOrigin = new Point(origin.X + (_boxMargin / 2), origin.Y);
var metrics = GetSize(double.PositiveInfinity);
- var r = new Rect(newOrigin.X - 0.5, newOrigin.Y, metrics.Width + 2, metrics.Height);
+ var r = new Rect(origin.X, origin.Y, metrics.Width, metrics.Height);
drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f);
base.Draw(drawingContext, newOrigin);
}
| 7 | Fixed margins for the box displayed for ControlCharacters | 6 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10059949 | <NME> SingleCharacterElementGenerator.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.CodeAnalysis;
using Avalonia;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Utilities;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
// This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions.
/// <summary>
/// Element generator that displays · for spaces and » for tabs and a box for control characters.
/// </summary>
/// <remarks>
/// This element generator is present in every TextView by default; the enabled features can be configured using the
/// <see cref="TextEditorOptions"/>.
/// </remarks>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")]
internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator
{
/// <summary>
/// Gets/Sets whether to show · for spaces.
/// </summary>
public bool ShowSpaces { get; set; }
/// <summary>
/// Gets/Sets whether to show » for tabs.
/// </summary>
public bool ShowTabs { get; set; }
/// <summary>
/// Gets/Sets whether to show a box with the hex code for control characters.
/// </summary>
public bool ShowBoxForControlCharacters { get; set; }
/// <summary>
/// Creates a new SingleCharacterElementGenerator instance.
/// </summary>
public SingleCharacterElementGenerator()
{
ShowSpaces = true;
ShowTabs = true;
ShowBoxForControlCharacters = true;
}
void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options)
{
ShowSpaces = options.ShowSpaces;
ShowTabs = options.ShowTabs;
ShowBoxForControlCharacters = options.ShowBoxForControlCharacters;
}
public override int GetFirstInterestedOffset(int startOffset)
{
var endLine = CurrentContext.VisualLine.LastDocumentLine;
var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset);
for (var i = 0; i < relevantText.Count; i++) {
var c = relevantText.Text[relevantText.Offset + i];
switch (c) {
case ' ':
if (ShowSpaces)
return startOffset + i;
break;
case '\t':
if (ShowTabs)
return startOffset + i;
break;
default:
if (ShowBoxForControlCharacters && char.IsControl(c)) {
return startOffset + i;
}
break;
}
}
return -1;
}
public override VisualLineElement ConstructElement(int offset)
{
var c = CurrentContext.Document.GetCharAt(offset);
if (ShowSpaces && c == ' ')
{
var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties);
runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush);
return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter(
CurrentContext.TextView.Options.ShowSpacesGlyph,
runProperties));
}
else if (ShowTabs && c == '\t')
{
var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties);
runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush);
return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter(
CurrentContext.TextView.Options.ShowTabsGlyph,
runProperties));
}
else if (ShowBoxForControlCharacters && char.IsControl(c))
{
var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties);
runProperties.SetForegroundBrush(Brushes.White);
var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView);
var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties);
return new SpecialCharacterBoxElement(text);
}
return null;
}
private sealed class SpaceTextElement : FormattedTextElement
{
public SpaceTextElement(TextLine textLine) : base(textLine, 1)
{
}
public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode)
{
if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint)
return base.GetNextCaretPosition(visualColumn, direction, mode);
else
return -1;
}
public override bool IsWhitespace(int visualColumn)
{
return true;
}
}
private sealed class TabTextElement : VisualLineElement
{
internal readonly TextLine Text;
public TabTextElement(TextLine text) : base(2, 1)
{
Text = text;
}
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
// the TabTextElement consists of two TextRuns:
// first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation
if (startVisualColumn == VisualColumn)
return new TabGlyphRun(this, TextRunProperties);
else if (startVisualColumn == VisualColumn + 1)
return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties);
else
throw new ArgumentOutOfRangeException(nameof(startVisualColumn));
}
public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode)
{
if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint)
return base.GetNextCaretPosition(visualColumn, direction, mode);
else
return -1;
}
public override bool IsWhitespace(int visualColumn)
{
return true;
}
}
private sealed class TabGlyphRun : DrawableTextRun
{
private readonly TabTextElement _element;
public TabGlyphRun(TabTextElement element, TextRunProperties properties)
{
if (properties == null)
throw new ArgumentNullException(nameof(properties));
Properties = properties;
_element = element;
}
public override TextRunProperties Properties { get; }
public override double Baseline => _element.Text.Baseline;
public override Size Size => Size.Empty;
public override void Draw(DrawingContext drawingContext, Point origin)
{
_element.Text.Draw(drawingContext, origin);
}
}
private sealed class SpecialCharacterBoxElement : FormattedTextElement
{
public SpecialCharacterBoxElement(TextLine text) : base(text, 1)
{
}
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
return new SpecialCharacterTextRun(this, TextRunProperties);
}
}
private sealed class SpecialCharacterTextRun : FormattedTextRun
{
private static readonly ISolidColorBrush DarkGrayBrush;
static SpecialCharacterTextRun()
{
DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128));
}
public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties)
: base(element, properties)
{
}
public override Rect ComputeBoundingBox()
{
var r = base.ComputeBoundingBox();
return r.WithWidth(r.Width + 3);
}
public override void Draw(DrawingContext drawingContext, Point origin)
{
var newOrigin = new Point(origin.X + 1.5, origin.Y);
var metrics = GetSize(double.PositiveInfinity);
var r = new Rect(newOrigin.X - 0.5, newOrigin.Y, metrics.Width + 2, metrics.Height);
drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f);
base.Draw(drawingContext, newOrigin);
}
var newOrigin = new Point(x + (BoxMargin / 2), y);
var (width, height) = Size;
var r = new Rect(x, y, width, height);
drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f);
base.Draw(drawingContext, newOrigin);
}
}
}
}
<MSG> Fixed margins for the box displayed for ControlCharacters
<DFF> @@ -225,11 +225,12 @@ namespace AvaloniaEdit.Rendering
private sealed class SpecialCharacterTextRun : FormattedTextRun
{
+ private const double _boxMargin = 3;
private static readonly ISolidColorBrush DarkGrayBrush;
static SpecialCharacterTextRun()
{
- DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128));
+ DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128));
}
public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties)
@@ -237,17 +238,17 @@ namespace AvaloniaEdit.Rendering
{
}
- public override Rect ComputeBoundingBox()
+ public override Size GetSize(double remainingParagraphWidth)
{
- var r = base.ComputeBoundingBox();
- return r.WithWidth(r.Width + 3);
+ var s = base.GetSize(remainingParagraphWidth);
+ return s.WithWidth(s.Width + _boxMargin);
}
public override void Draw(DrawingContext drawingContext, Point origin)
{
- var newOrigin = new Point(origin.X + 1.5, origin.Y);
+ var newOrigin = new Point(origin.X + (_boxMargin / 2), origin.Y);
var metrics = GetSize(double.PositiveInfinity);
- var r = new Rect(newOrigin.X - 0.5, newOrigin.Y, metrics.Width + 2, metrics.Height);
+ var r = new Rect(origin.X, origin.Y, metrics.Width, metrics.Height);
drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f);
base.Draw(drawingContext, newOrigin);
}
| 7 | Fixed margins for the box displayed for ControlCharacters | 6 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.