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
10060750
<NME> TextFormatterFactory.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils { /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> 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> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) var formattedText = new FormattedText { Text = text, Typeface = new Typeface(typeface), FontSize = emSize.Value }; FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> Merge pull request #110 from HendrikMennen/fix-memory-leak fix memory leak <DFF> @@ -59,7 +59,7 @@ namespace AvaloniaEdit.Utils var formattedText = new FormattedText { Text = text, - Typeface = new Typeface(typeface), + Typeface = FontManager.Current.GetOrAddTypeface(typeface), FontSize = emSize.Value };
1
Merge pull request #110 from HendrikMennen/fix-memory-leak
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060751
<NME> TextFormatterFactory.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils { /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> 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> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) var formattedText = new FormattedText { Text = text, Typeface = new Typeface(typeface), FontSize = emSize.Value }; FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> Merge pull request #110 from HendrikMennen/fix-memory-leak fix memory leak <DFF> @@ -59,7 +59,7 @@ namespace AvaloniaEdit.Utils var formattedText = new FormattedText { Text = text, - Typeface = new Typeface(typeface), + Typeface = FontManager.Current.GetOrAddTypeface(typeface), FontSize = emSize.Value };
1
Merge pull request #110 from HendrikMennen/fix-memory-leak
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060752
<NME> TextFormatterFactory.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils { /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> 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> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) var formattedText = new FormattedText { Text = text, Typeface = new Typeface(typeface), FontSize = emSize.Value }; FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> Merge pull request #110 from HendrikMennen/fix-memory-leak fix memory leak <DFF> @@ -59,7 +59,7 @@ namespace AvaloniaEdit.Utils var formattedText = new FormattedText { Text = text, - Typeface = new Typeface(typeface), + Typeface = FontManager.Current.GetOrAddTypeface(typeface), FontSize = emSize.Value };
1
Merge pull request #110 from HendrikMennen/fix-memory-leak
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060753
<NME> TextFormatterFactory.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils { /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> 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> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) var formattedText = new FormattedText { Text = text, Typeface = new Typeface(typeface), FontSize = emSize.Value }; FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> Merge pull request #110 from HendrikMennen/fix-memory-leak fix memory leak <DFF> @@ -59,7 +59,7 @@ namespace AvaloniaEdit.Utils var formattedText = new FormattedText { Text = text, - Typeface = new Typeface(typeface), + Typeface = FontManager.Current.GetOrAddTypeface(typeface), FontSize = emSize.Value };
1
Merge pull request #110 from HendrikMennen/fix-memory-leak
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060754
<NME> TextFormatterFactory.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils { /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> 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> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) var formattedText = new FormattedText { Text = text, Typeface = new Typeface(typeface), FontSize = emSize.Value }; FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> Merge pull request #110 from HendrikMennen/fix-memory-leak fix memory leak <DFF> @@ -59,7 +59,7 @@ namespace AvaloniaEdit.Utils var formattedText = new FormattedText { Text = text, - Typeface = new Typeface(typeface), + Typeface = FontManager.Current.GetOrAddTypeface(typeface), FontSize = emSize.Value };
1
Merge pull request #110 from HendrikMennen/fix-memory-leak
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060755
<NME> TextFormatterFactory.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils { /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> 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> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) var formattedText = new FormattedText { Text = text, Typeface = new Typeface(typeface), FontSize = emSize.Value }; FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> Merge pull request #110 from HendrikMennen/fix-memory-leak fix memory leak <DFF> @@ -59,7 +59,7 @@ namespace AvaloniaEdit.Utils var formattedText = new FormattedText { Text = text, - Typeface = new Typeface(typeface), + Typeface = FontManager.Current.GetOrAddTypeface(typeface), FontSize = emSize.Value };
1
Merge pull request #110 from HendrikMennen/fix-memory-leak
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060756
<NME> TextFormatterFactory.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils { /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> 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> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) var formattedText = new FormattedText { Text = text, Typeface = new Typeface(typeface), FontSize = emSize.Value }; FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> Merge pull request #110 from HendrikMennen/fix-memory-leak fix memory leak <DFF> @@ -59,7 +59,7 @@ namespace AvaloniaEdit.Utils var formattedText = new FormattedText { Text = text, - Typeface = new Typeface(typeface), + Typeface = FontManager.Current.GetOrAddTypeface(typeface), FontSize = emSize.Value };
1
Merge pull request #110 from HendrikMennen/fix-memory-leak
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060757
<NME> TextFormatterFactory.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils { /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> 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> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) var formattedText = new FormattedText { Text = text, Typeface = new Typeface(typeface), FontSize = emSize.Value }; FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> Merge pull request #110 from HendrikMennen/fix-memory-leak fix memory leak <DFF> @@ -59,7 +59,7 @@ namespace AvaloniaEdit.Utils var formattedText = new FormattedText { Text = text, - Typeface = new Typeface(typeface), + Typeface = FontManager.Current.GetOrAddTypeface(typeface), FontSize = emSize.Value };
1
Merge pull request #110 from HendrikMennen/fix-memory-leak
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060758
<NME> TextFormatterFactory.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils { /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> 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> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) var formattedText = new FormattedText { Text = text, Typeface = new Typeface(typeface), FontSize = emSize.Value }; FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> Merge pull request #110 from HendrikMennen/fix-memory-leak fix memory leak <DFF> @@ -59,7 +59,7 @@ namespace AvaloniaEdit.Utils var formattedText = new FormattedText { Text = text, - Typeface = new Typeface(typeface), + Typeface = FontManager.Current.GetOrAddTypeface(typeface), FontSize = emSize.Value };
1
Merge pull request #110 from HendrikMennen/fix-memory-leak
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060759
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } public int BackgroundColor { get; set; } public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } return; } var formattedOffset = 0; var endOffset = line.EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> fix theme change. <DFF> @@ -36,6 +36,11 @@ namespace AvaloniaEdit.TextMate return; } + if (!_brushCache.ContainsKey(Foreground)) + { + return; + } + var formattedOffset = 0; var endOffset = line.EndOffset;
5
fix theme change.
0
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10060760
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } public int BackgroundColor { get; set; } public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } return; } var formattedOffset = 0; var endOffset = line.EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> fix theme change. <DFF> @@ -36,6 +36,11 @@ namespace AvaloniaEdit.TextMate return; } + if (!_brushCache.ContainsKey(Foreground)) + { + return; + } + var formattedOffset = 0; var endOffset = line.EndOffset;
5
fix theme change.
0
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10060761
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } public int BackgroundColor { get; set; } public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } return; } var formattedOffset = 0; var endOffset = line.EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> fix theme change. <DFF> @@ -36,6 +36,11 @@ namespace AvaloniaEdit.TextMate return; } + if (!_brushCache.ContainsKey(Foreground)) + { + return; + } + var formattedOffset = 0; var endOffset = line.EndOffset;
5
fix theme change.
0
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10060762
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } public int BackgroundColor { get; set; } public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } return; } var formattedOffset = 0; var endOffset = line.EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> fix theme change. <DFF> @@ -36,6 +36,11 @@ namespace AvaloniaEdit.TextMate return; } + if (!_brushCache.ContainsKey(Foreground)) + { + return; + } + var formattedOffset = 0; var endOffset = line.EndOffset;
5
fix theme change.
0
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10060763
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } public int BackgroundColor { get; set; } public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } return; } var formattedOffset = 0; var endOffset = line.EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> fix theme change. <DFF> @@ -36,6 +36,11 @@ namespace AvaloniaEdit.TextMate return; } + if (!_brushCache.ContainsKey(Foreground)) + { + return; + } + var formattedOffset = 0; var endOffset = line.EndOffset;
5
fix theme change.
0
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10060764
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } public int BackgroundColor { get; set; } public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } return; } var formattedOffset = 0; var endOffset = line.EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> fix theme change. <DFF> @@ -36,6 +36,11 @@ namespace AvaloniaEdit.TextMate return; } + if (!_brushCache.ContainsKey(Foreground)) + { + return; + } + var formattedOffset = 0; var endOffset = line.EndOffset;
5
fix theme change.
0
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10060765
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } public int BackgroundColor { get; set; } public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } return; } var formattedOffset = 0; var endOffset = line.EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> fix theme change. <DFF> @@ -36,6 +36,11 @@ namespace AvaloniaEdit.TextMate return; } + if (!_brushCache.ContainsKey(Foreground)) + { + return; + } + var formattedOffset = 0; var endOffset = line.EndOffset;
5
fix theme change.
0
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10060766
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } public int BackgroundColor { get; set; } public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } return; } var formattedOffset = 0; var endOffset = line.EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> fix theme change. <DFF> @@ -36,6 +36,11 @@ namespace AvaloniaEdit.TextMate return; } + if (!_brushCache.ContainsKey(Foreground)) + { + return; + } + var formattedOffset = 0; var endOffset = line.EndOffset;
5
fix theme change.
0
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10060767
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } public int BackgroundColor { get; set; } public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } return; } var formattedOffset = 0; var endOffset = line.EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> fix theme change. <DFF> @@ -36,6 +36,11 @@ namespace AvaloniaEdit.TextMate return; } + if (!_brushCache.ContainsKey(Foreground)) + { + return; + } + var formattedOffset = 0; var endOffset = line.EndOffset;
5
fix theme change.
0
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10060768
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } public int BackgroundColor { get; set; } public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } return; } var formattedOffset = 0; var endOffset = line.EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> fix theme change. <DFF> @@ -36,6 +36,11 @@ namespace AvaloniaEdit.TextMate return; } + if (!_brushCache.ContainsKey(Foreground)) + { + return; + } + var formattedOffset = 0; var endOffset = line.EndOffset;
5
fix theme change.
0
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10060769
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } public int BackgroundColor { get; set; } public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } return; } var formattedOffset = 0; var endOffset = line.EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> fix theme change. <DFF> @@ -36,6 +36,11 @@ namespace AvaloniaEdit.TextMate return; } + if (!_brushCache.ContainsKey(Foreground)) + { + return; + } + var formattedOffset = 0; var endOffset = line.EndOffset;
5
fix theme change.
0
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10060770
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } public int BackgroundColor { get; set; } public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } return; } var formattedOffset = 0; var endOffset = line.EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> fix theme change. <DFF> @@ -36,6 +36,11 @@ namespace AvaloniaEdit.TextMate return; } + if (!_brushCache.ContainsKey(Foreground)) + { + return; + } + var formattedOffset = 0; var endOffset = line.EndOffset;
5
fix theme change.
0
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10060771
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } public int BackgroundColor { get; set; } public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } return; } var formattedOffset = 0; var endOffset = line.EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> fix theme change. <DFF> @@ -36,6 +36,11 @@ namespace AvaloniaEdit.TextMate return; } + if (!_brushCache.ContainsKey(Foreground)) + { + return; + } + var formattedOffset = 0; var endOffset = line.EndOffset;
5
fix theme change.
0
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10060772
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } public int BackgroundColor { get; set; } public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } return; } var formattedOffset = 0; var endOffset = line.EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> fix theme change. <DFF> @@ -36,6 +36,11 @@ namespace AvaloniaEdit.TextMate return; } + if (!_brushCache.ContainsKey(Foreground)) + { + return; + } + var formattedOffset = 0; var endOffset = line.EndOffset;
5
fix theme change.
0
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10060773
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } public int BackgroundColor { get; set; } public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } return; } var formattedOffset = 0; var endOffset = line.EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> fix theme change. <DFF> @@ -36,6 +36,11 @@ namespace AvaloniaEdit.TextMate return; } + if (!_brushCache.ContainsKey(Foreground)) + { + return; + } + var formattedOffset = 0; var endOffset = line.EndOffset;
5
fix theme change.
0
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10060774
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>11.0.999-cibuild0024027-beta</Version> </PropertyGroup> </Project> <MSG> Bump version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>11.0.999-cibuild0024027-beta</Version> + <Version>11.0.999-cibuild0024032-beta</Version> </PropertyGroup> </Project>
1
Bump version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10060775
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>11.0.999-cibuild0024027-beta</Version> </PropertyGroup> </Project> <MSG> Bump version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>11.0.999-cibuild0024027-beta</Version> + <Version>11.0.999-cibuild0024032-beta</Version> </PropertyGroup> </Project>
1
Bump version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10060776
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>11.0.999-cibuild0024027-beta</Version> </PropertyGroup> </Project> <MSG> Bump version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>11.0.999-cibuild0024027-beta</Version> + <Version>11.0.999-cibuild0024032-beta</Version> </PropertyGroup> </Project>
1
Bump version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10060777
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>11.0.999-cibuild0024027-beta</Version> </PropertyGroup> </Project> <MSG> Bump version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>11.0.999-cibuild0024027-beta</Version> + <Version>11.0.999-cibuild0024032-beta</Version> </PropertyGroup> </Project>
1
Bump version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10060778
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>11.0.999-cibuild0024027-beta</Version> </PropertyGroup> </Project> <MSG> Bump version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>11.0.999-cibuild0024027-beta</Version> + <Version>11.0.999-cibuild0024032-beta</Version> </PropertyGroup> </Project>
1
Bump version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10060779
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>11.0.999-cibuild0024027-beta</Version> </PropertyGroup> </Project> <MSG> Bump version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>11.0.999-cibuild0024027-beta</Version> + <Version>11.0.999-cibuild0024032-beta</Version> </PropertyGroup> </Project>
1
Bump version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10060780
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>11.0.999-cibuild0024027-beta</Version> </PropertyGroup> </Project> <MSG> Bump version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>11.0.999-cibuild0024027-beta</Version> + <Version>11.0.999-cibuild0024032-beta</Version> </PropertyGroup> </Project>
1
Bump version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10060781
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>11.0.999-cibuild0024027-beta</Version> </PropertyGroup> </Project> <MSG> Bump version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>11.0.999-cibuild0024027-beta</Version> + <Version>11.0.999-cibuild0024032-beta</Version> </PropertyGroup> </Project>
1
Bump version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10060782
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>11.0.999-cibuild0024027-beta</Version> </PropertyGroup> </Project> <MSG> Bump version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>11.0.999-cibuild0024027-beta</Version> + <Version>11.0.999-cibuild0024032-beta</Version> </PropertyGroup> </Project>
1
Bump version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10060783
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>11.0.999-cibuild0024027-beta</Version> </PropertyGroup> </Project> <MSG> Bump version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>11.0.999-cibuild0024027-beta</Version> + <Version>11.0.999-cibuild0024032-beta</Version> </PropertyGroup> </Project>
1
Bump version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10060784
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>11.0.999-cibuild0024027-beta</Version> </PropertyGroup> </Project> <MSG> Bump version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>11.0.999-cibuild0024027-beta</Version> + <Version>11.0.999-cibuild0024032-beta</Version> </PropertyGroup> </Project>
1
Bump version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10060785
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>11.0.999-cibuild0024027-beta</Version> </PropertyGroup> </Project> <MSG> Bump version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>11.0.999-cibuild0024027-beta</Version> + <Version>11.0.999-cibuild0024032-beta</Version> </PropertyGroup> </Project>
1
Bump version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10060786
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>11.0.999-cibuild0024027-beta</Version> </PropertyGroup> </Project> <MSG> Bump version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>11.0.999-cibuild0024027-beta</Version> + <Version>11.0.999-cibuild0024032-beta</Version> </PropertyGroup> </Project>
1
Bump version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10060787
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>11.0.999-cibuild0024027-beta</Version> </PropertyGroup> </Project> <MSG> Bump version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>11.0.999-cibuild0024027-beta</Version> + <Version>11.0.999-cibuild0024032-beta</Version> </PropertyGroup> </Project>
1
Bump version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10060788
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>11.0.999-cibuild0024027-beta</Version> </PropertyGroup> </Project> <MSG> Bump version <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>11.0.999-cibuild0024027-beta</AvaloniaVersion> <TextMateSharpVersion>1.0.43</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>11.0.999-cibuild0024027-beta</Version> + <Version>11.0.999-cibuild0024032-beta</Version> </PropertyGroup> </Project>
1
Bump version
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10060789
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion /// </summary> public void ScrollTo(int line, int column) { //const double MinimumScrollFraction = 0.3; //ScrollTo(line, column, VisualYPosition.LineMiddle, // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { /*TextView textView = textArea.TextView; TextDocument document = textView.Document; if (scrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; IScrollInfo scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) } } Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > minimumScrollFraction * scrollViewer.ViewportHeight) { scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); } if (column > 0) { if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > minimumScrollFraction * scrollViewer.ViewportWidth) { scrollViewer.ScrollToHorizontalOffset(horizontalPos); } } else { scrollViewer.ScrollToHorizontalOffset(0); } } }*/ } } } TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #235 from AvaloniaUI/fix-149 Enable ScrollTo functionality <DFF> @@ -1169,9 +1169,9 @@ namespace AvaloniaEdit /// </summary> public void ScrollTo(int line, int column) { - //const double MinimumScrollFraction = 0.3; - //ScrollTo(line, column, VisualYPosition.LineMiddle, - // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); + const double MinimumScrollFraction = 0.3; + ScrollTo(line, column, VisualYPosition.LineMiddle, + null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> @@ -1186,16 +1186,16 @@ namespace AvaloniaEdit public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { - /*TextView textView = textArea.TextView; + TextView textView = textArea.TextView; TextDocument document = textView.Document; - if (scrollViewer != null && document != null) + if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; - IScrollInfo scrollInfo = textView; + ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll @@ -1214,32 +1214,40 @@ namespace AvaloniaEdit } } - Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), + Point p = textArea.TextView.GetVisualPosition( + new TextViewPosition(line, Math.Max(1, column)), yPositionMode); + + double targetX = ScrollViewer.Offset.X; + double targetY = ScrollViewer.Offset.Y; + double verticalPos = p.Y - referencedVerticalViewPortOffset; - if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > - minimumScrollFraction * scrollViewer.ViewportHeight) + if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > + minimumScrollFraction * ScrollViewer.Viewport.Height) { - scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); + targetY = Math.Max(0, verticalPos); } if (column > 0) { - if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) + if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { - double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); - if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > - minimumScrollFraction * scrollViewer.ViewportWidth) + double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); + if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > + minimumScrollFraction * ScrollViewer.Viewport.Width) { - scrollViewer.ScrollToHorizontalOffset(horizontalPos); + targetX = 0; } } else { - scrollViewer.ScrollToHorizontalOffset(0); + targetX = 0; } } - }*/ + + if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) + ScrollViewer.Offset = new Vector(targetX, targetY); + } } } }
25
Merge pull request #235 from AvaloniaUI/fix-149
17
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060790
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion /// </summary> public void ScrollTo(int line, int column) { //const double MinimumScrollFraction = 0.3; //ScrollTo(line, column, VisualYPosition.LineMiddle, // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { /*TextView textView = textArea.TextView; TextDocument document = textView.Document; if (scrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; IScrollInfo scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) } } Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > minimumScrollFraction * scrollViewer.ViewportHeight) { scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); } if (column > 0) { if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > minimumScrollFraction * scrollViewer.ViewportWidth) { scrollViewer.ScrollToHorizontalOffset(horizontalPos); } } else { scrollViewer.ScrollToHorizontalOffset(0); } } }*/ } } } TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #235 from AvaloniaUI/fix-149 Enable ScrollTo functionality <DFF> @@ -1169,9 +1169,9 @@ namespace AvaloniaEdit /// </summary> public void ScrollTo(int line, int column) { - //const double MinimumScrollFraction = 0.3; - //ScrollTo(line, column, VisualYPosition.LineMiddle, - // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); + const double MinimumScrollFraction = 0.3; + ScrollTo(line, column, VisualYPosition.LineMiddle, + null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> @@ -1186,16 +1186,16 @@ namespace AvaloniaEdit public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { - /*TextView textView = textArea.TextView; + TextView textView = textArea.TextView; TextDocument document = textView.Document; - if (scrollViewer != null && document != null) + if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; - IScrollInfo scrollInfo = textView; + ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll @@ -1214,32 +1214,40 @@ namespace AvaloniaEdit } } - Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), + Point p = textArea.TextView.GetVisualPosition( + new TextViewPosition(line, Math.Max(1, column)), yPositionMode); + + double targetX = ScrollViewer.Offset.X; + double targetY = ScrollViewer.Offset.Y; + double verticalPos = p.Y - referencedVerticalViewPortOffset; - if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > - minimumScrollFraction * scrollViewer.ViewportHeight) + if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > + minimumScrollFraction * ScrollViewer.Viewport.Height) { - scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); + targetY = Math.Max(0, verticalPos); } if (column > 0) { - if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) + if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { - double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); - if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > - minimumScrollFraction * scrollViewer.ViewportWidth) + double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); + if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > + minimumScrollFraction * ScrollViewer.Viewport.Width) { - scrollViewer.ScrollToHorizontalOffset(horizontalPos); + targetX = 0; } } else { - scrollViewer.ScrollToHorizontalOffset(0); + targetX = 0; } } - }*/ + + if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) + ScrollViewer.Offset = new Vector(targetX, targetY); + } } } }
25
Merge pull request #235 from AvaloniaUI/fix-149
17
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060791
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion /// </summary> public void ScrollTo(int line, int column) { //const double MinimumScrollFraction = 0.3; //ScrollTo(line, column, VisualYPosition.LineMiddle, // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { /*TextView textView = textArea.TextView; TextDocument document = textView.Document; if (scrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; IScrollInfo scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) } } Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > minimumScrollFraction * scrollViewer.ViewportHeight) { scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); } if (column > 0) { if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > minimumScrollFraction * scrollViewer.ViewportWidth) { scrollViewer.ScrollToHorizontalOffset(horizontalPos); } } else { scrollViewer.ScrollToHorizontalOffset(0); } } }*/ } } } TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #235 from AvaloniaUI/fix-149 Enable ScrollTo functionality <DFF> @@ -1169,9 +1169,9 @@ namespace AvaloniaEdit /// </summary> public void ScrollTo(int line, int column) { - //const double MinimumScrollFraction = 0.3; - //ScrollTo(line, column, VisualYPosition.LineMiddle, - // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); + const double MinimumScrollFraction = 0.3; + ScrollTo(line, column, VisualYPosition.LineMiddle, + null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> @@ -1186,16 +1186,16 @@ namespace AvaloniaEdit public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { - /*TextView textView = textArea.TextView; + TextView textView = textArea.TextView; TextDocument document = textView.Document; - if (scrollViewer != null && document != null) + if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; - IScrollInfo scrollInfo = textView; + ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll @@ -1214,32 +1214,40 @@ namespace AvaloniaEdit } } - Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), + Point p = textArea.TextView.GetVisualPosition( + new TextViewPosition(line, Math.Max(1, column)), yPositionMode); + + double targetX = ScrollViewer.Offset.X; + double targetY = ScrollViewer.Offset.Y; + double verticalPos = p.Y - referencedVerticalViewPortOffset; - if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > - minimumScrollFraction * scrollViewer.ViewportHeight) + if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > + minimumScrollFraction * ScrollViewer.Viewport.Height) { - scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); + targetY = Math.Max(0, verticalPos); } if (column > 0) { - if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) + if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { - double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); - if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > - minimumScrollFraction * scrollViewer.ViewportWidth) + double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); + if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > + minimumScrollFraction * ScrollViewer.Viewport.Width) { - scrollViewer.ScrollToHorizontalOffset(horizontalPos); + targetX = 0; } } else { - scrollViewer.ScrollToHorizontalOffset(0); + targetX = 0; } } - }*/ + + if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) + ScrollViewer.Offset = new Vector(targetX, targetY); + } } } }
25
Merge pull request #235 from AvaloniaUI/fix-149
17
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060792
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion /// </summary> public void ScrollTo(int line, int column) { //const double MinimumScrollFraction = 0.3; //ScrollTo(line, column, VisualYPosition.LineMiddle, // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { /*TextView textView = textArea.TextView; TextDocument document = textView.Document; if (scrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; IScrollInfo scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) } } Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > minimumScrollFraction * scrollViewer.ViewportHeight) { scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); } if (column > 0) { if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > minimumScrollFraction * scrollViewer.ViewportWidth) { scrollViewer.ScrollToHorizontalOffset(horizontalPos); } } else { scrollViewer.ScrollToHorizontalOffset(0); } } }*/ } } } TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #235 from AvaloniaUI/fix-149 Enable ScrollTo functionality <DFF> @@ -1169,9 +1169,9 @@ namespace AvaloniaEdit /// </summary> public void ScrollTo(int line, int column) { - //const double MinimumScrollFraction = 0.3; - //ScrollTo(line, column, VisualYPosition.LineMiddle, - // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); + const double MinimumScrollFraction = 0.3; + ScrollTo(line, column, VisualYPosition.LineMiddle, + null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> @@ -1186,16 +1186,16 @@ namespace AvaloniaEdit public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { - /*TextView textView = textArea.TextView; + TextView textView = textArea.TextView; TextDocument document = textView.Document; - if (scrollViewer != null && document != null) + if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; - IScrollInfo scrollInfo = textView; + ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll @@ -1214,32 +1214,40 @@ namespace AvaloniaEdit } } - Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), + Point p = textArea.TextView.GetVisualPosition( + new TextViewPosition(line, Math.Max(1, column)), yPositionMode); + + double targetX = ScrollViewer.Offset.X; + double targetY = ScrollViewer.Offset.Y; + double verticalPos = p.Y - referencedVerticalViewPortOffset; - if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > - minimumScrollFraction * scrollViewer.ViewportHeight) + if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > + minimumScrollFraction * ScrollViewer.Viewport.Height) { - scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); + targetY = Math.Max(0, verticalPos); } if (column > 0) { - if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) + if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { - double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); - if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > - minimumScrollFraction * scrollViewer.ViewportWidth) + double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); + if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > + minimumScrollFraction * ScrollViewer.Viewport.Width) { - scrollViewer.ScrollToHorizontalOffset(horizontalPos); + targetX = 0; } } else { - scrollViewer.ScrollToHorizontalOffset(0); + targetX = 0; } } - }*/ + + if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) + ScrollViewer.Offset = new Vector(targetX, targetY); + } } } }
25
Merge pull request #235 from AvaloniaUI/fix-149
17
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060793
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion /// </summary> public void ScrollTo(int line, int column) { //const double MinimumScrollFraction = 0.3; //ScrollTo(line, column, VisualYPosition.LineMiddle, // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { /*TextView textView = textArea.TextView; TextDocument document = textView.Document; if (scrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; IScrollInfo scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) } } Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > minimumScrollFraction * scrollViewer.ViewportHeight) { scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); } if (column > 0) { if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > minimumScrollFraction * scrollViewer.ViewportWidth) { scrollViewer.ScrollToHorizontalOffset(horizontalPos); } } else { scrollViewer.ScrollToHorizontalOffset(0); } } }*/ } } } TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #235 from AvaloniaUI/fix-149 Enable ScrollTo functionality <DFF> @@ -1169,9 +1169,9 @@ namespace AvaloniaEdit /// </summary> public void ScrollTo(int line, int column) { - //const double MinimumScrollFraction = 0.3; - //ScrollTo(line, column, VisualYPosition.LineMiddle, - // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); + const double MinimumScrollFraction = 0.3; + ScrollTo(line, column, VisualYPosition.LineMiddle, + null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> @@ -1186,16 +1186,16 @@ namespace AvaloniaEdit public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { - /*TextView textView = textArea.TextView; + TextView textView = textArea.TextView; TextDocument document = textView.Document; - if (scrollViewer != null && document != null) + if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; - IScrollInfo scrollInfo = textView; + ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll @@ -1214,32 +1214,40 @@ namespace AvaloniaEdit } } - Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), + Point p = textArea.TextView.GetVisualPosition( + new TextViewPosition(line, Math.Max(1, column)), yPositionMode); + + double targetX = ScrollViewer.Offset.X; + double targetY = ScrollViewer.Offset.Y; + double verticalPos = p.Y - referencedVerticalViewPortOffset; - if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > - minimumScrollFraction * scrollViewer.ViewportHeight) + if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > + minimumScrollFraction * ScrollViewer.Viewport.Height) { - scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); + targetY = Math.Max(0, verticalPos); } if (column > 0) { - if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) + if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { - double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); - if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > - minimumScrollFraction * scrollViewer.ViewportWidth) + double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); + if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > + minimumScrollFraction * ScrollViewer.Viewport.Width) { - scrollViewer.ScrollToHorizontalOffset(horizontalPos); + targetX = 0; } } else { - scrollViewer.ScrollToHorizontalOffset(0); + targetX = 0; } } - }*/ + + if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) + ScrollViewer.Offset = new Vector(targetX, targetY); + } } } }
25
Merge pull request #235 from AvaloniaUI/fix-149
17
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060794
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion /// </summary> public void ScrollTo(int line, int column) { //const double MinimumScrollFraction = 0.3; //ScrollTo(line, column, VisualYPosition.LineMiddle, // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { /*TextView textView = textArea.TextView; TextDocument document = textView.Document; if (scrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; IScrollInfo scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) } } Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > minimumScrollFraction * scrollViewer.ViewportHeight) { scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); } if (column > 0) { if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > minimumScrollFraction * scrollViewer.ViewportWidth) { scrollViewer.ScrollToHorizontalOffset(horizontalPos); } } else { scrollViewer.ScrollToHorizontalOffset(0); } } }*/ } } } TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #235 from AvaloniaUI/fix-149 Enable ScrollTo functionality <DFF> @@ -1169,9 +1169,9 @@ namespace AvaloniaEdit /// </summary> public void ScrollTo(int line, int column) { - //const double MinimumScrollFraction = 0.3; - //ScrollTo(line, column, VisualYPosition.LineMiddle, - // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); + const double MinimumScrollFraction = 0.3; + ScrollTo(line, column, VisualYPosition.LineMiddle, + null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> @@ -1186,16 +1186,16 @@ namespace AvaloniaEdit public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { - /*TextView textView = textArea.TextView; + TextView textView = textArea.TextView; TextDocument document = textView.Document; - if (scrollViewer != null && document != null) + if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; - IScrollInfo scrollInfo = textView; + ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll @@ -1214,32 +1214,40 @@ namespace AvaloniaEdit } } - Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), + Point p = textArea.TextView.GetVisualPosition( + new TextViewPosition(line, Math.Max(1, column)), yPositionMode); + + double targetX = ScrollViewer.Offset.X; + double targetY = ScrollViewer.Offset.Y; + double verticalPos = p.Y - referencedVerticalViewPortOffset; - if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > - minimumScrollFraction * scrollViewer.ViewportHeight) + if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > + minimumScrollFraction * ScrollViewer.Viewport.Height) { - scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); + targetY = Math.Max(0, verticalPos); } if (column > 0) { - if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) + if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { - double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); - if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > - minimumScrollFraction * scrollViewer.ViewportWidth) + double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); + if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > + minimumScrollFraction * ScrollViewer.Viewport.Width) { - scrollViewer.ScrollToHorizontalOffset(horizontalPos); + targetX = 0; } } else { - scrollViewer.ScrollToHorizontalOffset(0); + targetX = 0; } } - }*/ + + if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) + ScrollViewer.Offset = new Vector(targetX, targetY); + } } } }
25
Merge pull request #235 from AvaloniaUI/fix-149
17
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060795
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion /// </summary> public void ScrollTo(int line, int column) { //const double MinimumScrollFraction = 0.3; //ScrollTo(line, column, VisualYPosition.LineMiddle, // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { /*TextView textView = textArea.TextView; TextDocument document = textView.Document; if (scrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; IScrollInfo scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) } } Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > minimumScrollFraction * scrollViewer.ViewportHeight) { scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); } if (column > 0) { if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > minimumScrollFraction * scrollViewer.ViewportWidth) { scrollViewer.ScrollToHorizontalOffset(horizontalPos); } } else { scrollViewer.ScrollToHorizontalOffset(0); } } }*/ } } } TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #235 from AvaloniaUI/fix-149 Enable ScrollTo functionality <DFF> @@ -1169,9 +1169,9 @@ namespace AvaloniaEdit /// </summary> public void ScrollTo(int line, int column) { - //const double MinimumScrollFraction = 0.3; - //ScrollTo(line, column, VisualYPosition.LineMiddle, - // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); + const double MinimumScrollFraction = 0.3; + ScrollTo(line, column, VisualYPosition.LineMiddle, + null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> @@ -1186,16 +1186,16 @@ namespace AvaloniaEdit public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { - /*TextView textView = textArea.TextView; + TextView textView = textArea.TextView; TextDocument document = textView.Document; - if (scrollViewer != null && document != null) + if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; - IScrollInfo scrollInfo = textView; + ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll @@ -1214,32 +1214,40 @@ namespace AvaloniaEdit } } - Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), + Point p = textArea.TextView.GetVisualPosition( + new TextViewPosition(line, Math.Max(1, column)), yPositionMode); + + double targetX = ScrollViewer.Offset.X; + double targetY = ScrollViewer.Offset.Y; + double verticalPos = p.Y - referencedVerticalViewPortOffset; - if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > - minimumScrollFraction * scrollViewer.ViewportHeight) + if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > + minimumScrollFraction * ScrollViewer.Viewport.Height) { - scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); + targetY = Math.Max(0, verticalPos); } if (column > 0) { - if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) + if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { - double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); - if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > - minimumScrollFraction * scrollViewer.ViewportWidth) + double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); + if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > + minimumScrollFraction * ScrollViewer.Viewport.Width) { - scrollViewer.ScrollToHorizontalOffset(horizontalPos); + targetX = 0; } } else { - scrollViewer.ScrollToHorizontalOffset(0); + targetX = 0; } } - }*/ + + if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) + ScrollViewer.Offset = new Vector(targetX, targetY); + } } } }
25
Merge pull request #235 from AvaloniaUI/fix-149
17
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060796
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion /// </summary> public void ScrollTo(int line, int column) { //const double MinimumScrollFraction = 0.3; //ScrollTo(line, column, VisualYPosition.LineMiddle, // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { /*TextView textView = textArea.TextView; TextDocument document = textView.Document; if (scrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; IScrollInfo scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) } } Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > minimumScrollFraction * scrollViewer.ViewportHeight) { scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); } if (column > 0) { if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > minimumScrollFraction * scrollViewer.ViewportWidth) { scrollViewer.ScrollToHorizontalOffset(horizontalPos); } } else { scrollViewer.ScrollToHorizontalOffset(0); } } }*/ } } } TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #235 from AvaloniaUI/fix-149 Enable ScrollTo functionality <DFF> @@ -1169,9 +1169,9 @@ namespace AvaloniaEdit /// </summary> public void ScrollTo(int line, int column) { - //const double MinimumScrollFraction = 0.3; - //ScrollTo(line, column, VisualYPosition.LineMiddle, - // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); + const double MinimumScrollFraction = 0.3; + ScrollTo(line, column, VisualYPosition.LineMiddle, + null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> @@ -1186,16 +1186,16 @@ namespace AvaloniaEdit public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { - /*TextView textView = textArea.TextView; + TextView textView = textArea.TextView; TextDocument document = textView.Document; - if (scrollViewer != null && document != null) + if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; - IScrollInfo scrollInfo = textView; + ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll @@ -1214,32 +1214,40 @@ namespace AvaloniaEdit } } - Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), + Point p = textArea.TextView.GetVisualPosition( + new TextViewPosition(line, Math.Max(1, column)), yPositionMode); + + double targetX = ScrollViewer.Offset.X; + double targetY = ScrollViewer.Offset.Y; + double verticalPos = p.Y - referencedVerticalViewPortOffset; - if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > - minimumScrollFraction * scrollViewer.ViewportHeight) + if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > + minimumScrollFraction * ScrollViewer.Viewport.Height) { - scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); + targetY = Math.Max(0, verticalPos); } if (column > 0) { - if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) + if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { - double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); - if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > - minimumScrollFraction * scrollViewer.ViewportWidth) + double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); + if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > + minimumScrollFraction * ScrollViewer.Viewport.Width) { - scrollViewer.ScrollToHorizontalOffset(horizontalPos); + targetX = 0; } } else { - scrollViewer.ScrollToHorizontalOffset(0); + targetX = 0; } } - }*/ + + if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) + ScrollViewer.Offset = new Vector(targetX, targetY); + } } } }
25
Merge pull request #235 from AvaloniaUI/fix-149
17
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060797
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion /// </summary> public void ScrollTo(int line, int column) { //const double MinimumScrollFraction = 0.3; //ScrollTo(line, column, VisualYPosition.LineMiddle, // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { /*TextView textView = textArea.TextView; TextDocument document = textView.Document; if (scrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; IScrollInfo scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) } } Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > minimumScrollFraction * scrollViewer.ViewportHeight) { scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); } if (column > 0) { if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > minimumScrollFraction * scrollViewer.ViewportWidth) { scrollViewer.ScrollToHorizontalOffset(horizontalPos); } } else { scrollViewer.ScrollToHorizontalOffset(0); } } }*/ } } } TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #235 from AvaloniaUI/fix-149 Enable ScrollTo functionality <DFF> @@ -1169,9 +1169,9 @@ namespace AvaloniaEdit /// </summary> public void ScrollTo(int line, int column) { - //const double MinimumScrollFraction = 0.3; - //ScrollTo(line, column, VisualYPosition.LineMiddle, - // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); + const double MinimumScrollFraction = 0.3; + ScrollTo(line, column, VisualYPosition.LineMiddle, + null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> @@ -1186,16 +1186,16 @@ namespace AvaloniaEdit public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { - /*TextView textView = textArea.TextView; + TextView textView = textArea.TextView; TextDocument document = textView.Document; - if (scrollViewer != null && document != null) + if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; - IScrollInfo scrollInfo = textView; + ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll @@ -1214,32 +1214,40 @@ namespace AvaloniaEdit } } - Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), + Point p = textArea.TextView.GetVisualPosition( + new TextViewPosition(line, Math.Max(1, column)), yPositionMode); + + double targetX = ScrollViewer.Offset.X; + double targetY = ScrollViewer.Offset.Y; + double verticalPos = p.Y - referencedVerticalViewPortOffset; - if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > - minimumScrollFraction * scrollViewer.ViewportHeight) + if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > + minimumScrollFraction * ScrollViewer.Viewport.Height) { - scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); + targetY = Math.Max(0, verticalPos); } if (column > 0) { - if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) + if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { - double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); - if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > - minimumScrollFraction * scrollViewer.ViewportWidth) + double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); + if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > + minimumScrollFraction * ScrollViewer.Viewport.Width) { - scrollViewer.ScrollToHorizontalOffset(horizontalPos); + targetX = 0; } } else { - scrollViewer.ScrollToHorizontalOffset(0); + targetX = 0; } } - }*/ + + if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) + ScrollViewer.Offset = new Vector(targetX, targetY); + } } } }
25
Merge pull request #235 from AvaloniaUI/fix-149
17
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060798
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion /// </summary> public void ScrollTo(int line, int column) { //const double MinimumScrollFraction = 0.3; //ScrollTo(line, column, VisualYPosition.LineMiddle, // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { /*TextView textView = textArea.TextView; TextDocument document = textView.Document; if (scrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; IScrollInfo scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) } } Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > minimumScrollFraction * scrollViewer.ViewportHeight) { scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); } if (column > 0) { if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > minimumScrollFraction * scrollViewer.ViewportWidth) { scrollViewer.ScrollToHorizontalOffset(horizontalPos); } } else { scrollViewer.ScrollToHorizontalOffset(0); } } }*/ } } } TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #235 from AvaloniaUI/fix-149 Enable ScrollTo functionality <DFF> @@ -1169,9 +1169,9 @@ namespace AvaloniaEdit /// </summary> public void ScrollTo(int line, int column) { - //const double MinimumScrollFraction = 0.3; - //ScrollTo(line, column, VisualYPosition.LineMiddle, - // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); + const double MinimumScrollFraction = 0.3; + ScrollTo(line, column, VisualYPosition.LineMiddle, + null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> @@ -1186,16 +1186,16 @@ namespace AvaloniaEdit public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { - /*TextView textView = textArea.TextView; + TextView textView = textArea.TextView; TextDocument document = textView.Document; - if (scrollViewer != null && document != null) + if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; - IScrollInfo scrollInfo = textView; + ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll @@ -1214,32 +1214,40 @@ namespace AvaloniaEdit } } - Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), + Point p = textArea.TextView.GetVisualPosition( + new TextViewPosition(line, Math.Max(1, column)), yPositionMode); + + double targetX = ScrollViewer.Offset.X; + double targetY = ScrollViewer.Offset.Y; + double verticalPos = p.Y - referencedVerticalViewPortOffset; - if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > - minimumScrollFraction * scrollViewer.ViewportHeight) + if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > + minimumScrollFraction * ScrollViewer.Viewport.Height) { - scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); + targetY = Math.Max(0, verticalPos); } if (column > 0) { - if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) + if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { - double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); - if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > - minimumScrollFraction * scrollViewer.ViewportWidth) + double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); + if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > + minimumScrollFraction * ScrollViewer.Viewport.Width) { - scrollViewer.ScrollToHorizontalOffset(horizontalPos); + targetX = 0; } } else { - scrollViewer.ScrollToHorizontalOffset(0); + targetX = 0; } } - }*/ + + if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) + ScrollViewer.Offset = new Vector(targetX, targetY); + } } } }
25
Merge pull request #235 from AvaloniaUI/fix-149
17
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060799
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion /// </summary> public void ScrollTo(int line, int column) { //const double MinimumScrollFraction = 0.3; //ScrollTo(line, column, VisualYPosition.LineMiddle, // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { /*TextView textView = textArea.TextView; TextDocument document = textView.Document; if (scrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; IScrollInfo scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) } } Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > minimumScrollFraction * scrollViewer.ViewportHeight) { scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); } if (column > 0) { if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > minimumScrollFraction * scrollViewer.ViewportWidth) { scrollViewer.ScrollToHorizontalOffset(horizontalPos); } } else { scrollViewer.ScrollToHorizontalOffset(0); } } }*/ } } } TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #235 from AvaloniaUI/fix-149 Enable ScrollTo functionality <DFF> @@ -1169,9 +1169,9 @@ namespace AvaloniaEdit /// </summary> public void ScrollTo(int line, int column) { - //const double MinimumScrollFraction = 0.3; - //ScrollTo(line, column, VisualYPosition.LineMiddle, - // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); + const double MinimumScrollFraction = 0.3; + ScrollTo(line, column, VisualYPosition.LineMiddle, + null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> @@ -1186,16 +1186,16 @@ namespace AvaloniaEdit public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { - /*TextView textView = textArea.TextView; + TextView textView = textArea.TextView; TextDocument document = textView.Document; - if (scrollViewer != null && document != null) + if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; - IScrollInfo scrollInfo = textView; + ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll @@ -1214,32 +1214,40 @@ namespace AvaloniaEdit } } - Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), + Point p = textArea.TextView.GetVisualPosition( + new TextViewPosition(line, Math.Max(1, column)), yPositionMode); + + double targetX = ScrollViewer.Offset.X; + double targetY = ScrollViewer.Offset.Y; + double verticalPos = p.Y - referencedVerticalViewPortOffset; - if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > - minimumScrollFraction * scrollViewer.ViewportHeight) + if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > + minimumScrollFraction * ScrollViewer.Viewport.Height) { - scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); + targetY = Math.Max(0, verticalPos); } if (column > 0) { - if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) + if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { - double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); - if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > - minimumScrollFraction * scrollViewer.ViewportWidth) + double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); + if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > + minimumScrollFraction * ScrollViewer.Viewport.Width) { - scrollViewer.ScrollToHorizontalOffset(horizontalPos); + targetX = 0; } } else { - scrollViewer.ScrollToHorizontalOffset(0); + targetX = 0; } } - }*/ + + if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) + ScrollViewer.Offset = new Vector(targetX, targetY); + } } } }
25
Merge pull request #235 from AvaloniaUI/fix-149
17
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060800
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion /// </summary> public void ScrollTo(int line, int column) { //const double MinimumScrollFraction = 0.3; //ScrollTo(line, column, VisualYPosition.LineMiddle, // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { /*TextView textView = textArea.TextView; TextDocument document = textView.Document; if (scrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; IScrollInfo scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) } } Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > minimumScrollFraction * scrollViewer.ViewportHeight) { scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); } if (column > 0) { if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > minimumScrollFraction * scrollViewer.ViewportWidth) { scrollViewer.ScrollToHorizontalOffset(horizontalPos); } } else { scrollViewer.ScrollToHorizontalOffset(0); } } }*/ } } } TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #235 from AvaloniaUI/fix-149 Enable ScrollTo functionality <DFF> @@ -1169,9 +1169,9 @@ namespace AvaloniaEdit /// </summary> public void ScrollTo(int line, int column) { - //const double MinimumScrollFraction = 0.3; - //ScrollTo(line, column, VisualYPosition.LineMiddle, - // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); + const double MinimumScrollFraction = 0.3; + ScrollTo(line, column, VisualYPosition.LineMiddle, + null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> @@ -1186,16 +1186,16 @@ namespace AvaloniaEdit public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { - /*TextView textView = textArea.TextView; + TextView textView = textArea.TextView; TextDocument document = textView.Document; - if (scrollViewer != null && document != null) + if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; - IScrollInfo scrollInfo = textView; + ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll @@ -1214,32 +1214,40 @@ namespace AvaloniaEdit } } - Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), + Point p = textArea.TextView.GetVisualPosition( + new TextViewPosition(line, Math.Max(1, column)), yPositionMode); + + double targetX = ScrollViewer.Offset.X; + double targetY = ScrollViewer.Offset.Y; + double verticalPos = p.Y - referencedVerticalViewPortOffset; - if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > - minimumScrollFraction * scrollViewer.ViewportHeight) + if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > + minimumScrollFraction * ScrollViewer.Viewport.Height) { - scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); + targetY = Math.Max(0, verticalPos); } if (column > 0) { - if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) + if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { - double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); - if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > - minimumScrollFraction * scrollViewer.ViewportWidth) + double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); + if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > + minimumScrollFraction * ScrollViewer.Viewport.Width) { - scrollViewer.ScrollToHorizontalOffset(horizontalPos); + targetX = 0; } } else { - scrollViewer.ScrollToHorizontalOffset(0); + targetX = 0; } } - }*/ + + if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) + ScrollViewer.Offset = new Vector(targetX, targetY); + } } } }
25
Merge pull request #235 from AvaloniaUI/fix-149
17
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060801
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion /// </summary> public void ScrollTo(int line, int column) { //const double MinimumScrollFraction = 0.3; //ScrollTo(line, column, VisualYPosition.LineMiddle, // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { /*TextView textView = textArea.TextView; TextDocument document = textView.Document; if (scrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; IScrollInfo scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) } } Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > minimumScrollFraction * scrollViewer.ViewportHeight) { scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); } if (column > 0) { if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > minimumScrollFraction * scrollViewer.ViewportWidth) { scrollViewer.ScrollToHorizontalOffset(horizontalPos); } } else { scrollViewer.ScrollToHorizontalOffset(0); } } }*/ } } } TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #235 from AvaloniaUI/fix-149 Enable ScrollTo functionality <DFF> @@ -1169,9 +1169,9 @@ namespace AvaloniaEdit /// </summary> public void ScrollTo(int line, int column) { - //const double MinimumScrollFraction = 0.3; - //ScrollTo(line, column, VisualYPosition.LineMiddle, - // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); + const double MinimumScrollFraction = 0.3; + ScrollTo(line, column, VisualYPosition.LineMiddle, + null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> @@ -1186,16 +1186,16 @@ namespace AvaloniaEdit public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { - /*TextView textView = textArea.TextView; + TextView textView = textArea.TextView; TextDocument document = textView.Document; - if (scrollViewer != null && document != null) + if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; - IScrollInfo scrollInfo = textView; + ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll @@ -1214,32 +1214,40 @@ namespace AvaloniaEdit } } - Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), + Point p = textArea.TextView.GetVisualPosition( + new TextViewPosition(line, Math.Max(1, column)), yPositionMode); + + double targetX = ScrollViewer.Offset.X; + double targetY = ScrollViewer.Offset.Y; + double verticalPos = p.Y - referencedVerticalViewPortOffset; - if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > - minimumScrollFraction * scrollViewer.ViewportHeight) + if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > + minimumScrollFraction * ScrollViewer.Viewport.Height) { - scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); + targetY = Math.Max(0, verticalPos); } if (column > 0) { - if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) + if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { - double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); - if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > - minimumScrollFraction * scrollViewer.ViewportWidth) + double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); + if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > + minimumScrollFraction * ScrollViewer.Viewport.Width) { - scrollViewer.ScrollToHorizontalOffset(horizontalPos); + targetX = 0; } } else { - scrollViewer.ScrollToHorizontalOffset(0); + targetX = 0; } } - }*/ + + if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) + ScrollViewer.Offset = new Vector(targetX, targetY); + } } } }
25
Merge pull request #235 from AvaloniaUI/fix-149
17
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060802
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion /// </summary> public void ScrollTo(int line, int column) { //const double MinimumScrollFraction = 0.3; //ScrollTo(line, column, VisualYPosition.LineMiddle, // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { /*TextView textView = textArea.TextView; TextDocument document = textView.Document; if (scrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; IScrollInfo scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) } } Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > minimumScrollFraction * scrollViewer.ViewportHeight) { scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); } if (column > 0) { if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > minimumScrollFraction * scrollViewer.ViewportWidth) { scrollViewer.ScrollToHorizontalOffset(horizontalPos); } } else { scrollViewer.ScrollToHorizontalOffset(0); } } }*/ } } } TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #235 from AvaloniaUI/fix-149 Enable ScrollTo functionality <DFF> @@ -1169,9 +1169,9 @@ namespace AvaloniaEdit /// </summary> public void ScrollTo(int line, int column) { - //const double MinimumScrollFraction = 0.3; - //ScrollTo(line, column, VisualYPosition.LineMiddle, - // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); + const double MinimumScrollFraction = 0.3; + ScrollTo(line, column, VisualYPosition.LineMiddle, + null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> @@ -1186,16 +1186,16 @@ namespace AvaloniaEdit public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { - /*TextView textView = textArea.TextView; + TextView textView = textArea.TextView; TextDocument document = textView.Document; - if (scrollViewer != null && document != null) + if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; - IScrollInfo scrollInfo = textView; + ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll @@ -1214,32 +1214,40 @@ namespace AvaloniaEdit } } - Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), + Point p = textArea.TextView.GetVisualPosition( + new TextViewPosition(line, Math.Max(1, column)), yPositionMode); + + double targetX = ScrollViewer.Offset.X; + double targetY = ScrollViewer.Offset.Y; + double verticalPos = p.Y - referencedVerticalViewPortOffset; - if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > - minimumScrollFraction * scrollViewer.ViewportHeight) + if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > + minimumScrollFraction * ScrollViewer.Viewport.Height) { - scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); + targetY = Math.Max(0, verticalPos); } if (column > 0) { - if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) + if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { - double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); - if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > - minimumScrollFraction * scrollViewer.ViewportWidth) + double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); + if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > + minimumScrollFraction * ScrollViewer.Viewport.Width) { - scrollViewer.ScrollToHorizontalOffset(horizontalPos); + targetX = 0; } } else { - scrollViewer.ScrollToHorizontalOffset(0); + targetX = 0; } } - }*/ + + if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) + ScrollViewer.Offset = new Vector(targetX, targetY); + } } } }
25
Merge pull request #235 from AvaloniaUI/fix-149
17
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060803
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion /// </summary> public void ScrollTo(int line, int column) { //const double MinimumScrollFraction = 0.3; //ScrollTo(line, column, VisualYPosition.LineMiddle, // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { /*TextView textView = textArea.TextView; TextDocument document = textView.Document; if (scrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; IScrollInfo scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) } } Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > minimumScrollFraction * scrollViewer.ViewportHeight) { scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); } if (column > 0) { if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > minimumScrollFraction * scrollViewer.ViewportWidth) { scrollViewer.ScrollToHorizontalOffset(horizontalPos); } } else { scrollViewer.ScrollToHorizontalOffset(0); } } }*/ } } } TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #235 from AvaloniaUI/fix-149 Enable ScrollTo functionality <DFF> @@ -1169,9 +1169,9 @@ namespace AvaloniaEdit /// </summary> public void ScrollTo(int line, int column) { - //const double MinimumScrollFraction = 0.3; - //ScrollTo(line, column, VisualYPosition.LineMiddle, - // null != scrollViewer ? scrollViewer.ViewportHeight / 2 : 0.0, MinimumScrollFraction); + const double MinimumScrollFraction = 0.3; + ScrollTo(line, column, VisualYPosition.LineMiddle, + null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> @@ -1186,16 +1186,16 @@ namespace AvaloniaEdit public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { - /*TextView textView = textArea.TextView; + TextView textView = textArea.TextView; TextDocument document = textView.Document; - if (scrollViewer != null && document != null) + if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; - IScrollInfo scrollInfo = textView; + ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll @@ -1214,32 +1214,40 @@ namespace AvaloniaEdit } } - Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), + Point p = textArea.TextView.GetVisualPosition( + new TextViewPosition(line, Math.Max(1, column)), yPositionMode); + + double targetX = ScrollViewer.Offset.X; + double targetY = ScrollViewer.Offset.Y; + double verticalPos = p.Y - referencedVerticalViewPortOffset; - if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > - minimumScrollFraction * scrollViewer.ViewportHeight) + if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > + minimumScrollFraction * ScrollViewer.Viewport.Height) { - scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); + targetY = Math.Max(0, verticalPos); } if (column > 0) { - if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) + if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { - double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); - if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > - minimumScrollFraction * scrollViewer.ViewportWidth) + double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); + if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > + minimumScrollFraction * ScrollViewer.Viewport.Width) { - scrollViewer.ScrollToHorizontalOffset(horizontalPos); + targetX = 0; } } else { - scrollViewer.ScrollToHorizontalOffset(0); + targetX = 0; } } - }*/ + + if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) + ScrollViewer.Offset = new Vector(targetX, targetY); + } } } }
25
Merge pull request #235 from AvaloniaUI/fix-149
17
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060804
<NME> TextLineRunTests.cs <BEF> ADDFILE <MSG> Added unit tests <DFF> @@ -0,0 +1,91 @@ +using Avalonia.Media; +using Avalonia.Platform; + +using AvaloniaEdit.AvaloniaMocks; +using AvaloniaEdit.Rendering; + +using Moq; + +using NUnit.Framework; + +using static AvaloniaEdit.Rendering.SingleCharacterElementGenerator; + +namespace AvaloniaEdit.Text +{ + [TestFixture] + internal class TextLineRunTests + { + [Test] + public void Text_Line_Run_Should_Have_Valid_Glyph_Widths() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "0123", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 2); + + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 0, run.GetDistanceFromCharacter(0)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 1, run.GetDistanceFromCharacter(1)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 2, run.GetDistanceFromCharacter(2)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 3, run.GetDistanceFromCharacter(3)); + } + + [Test] + public void Tab_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "\t", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 1); + + Assert.AreEqual(40, run.GetDistanceFromCharacter(1)); + } + + [Test] + public void TextEmbeddedObject_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + int runWidth = 50; + + TextLine textLine = Mock.Of<TextLine>( + t => t.WidthIncludingTrailingWhitespace == runWidth); + + SpecialCharacterTextRun f = new SpecialCharacterTextRun( + new FormattedTextElement("BEL", 1) { TextLine = textLine }, + CreateDefaultTextProperties()); + + Mock<TextSource> ts = new Mock<TextSource>(); + ts.Setup(s=> s.GetTextRun(It.IsAny<int>())).Returns(f); + + TextLineRun run = TextLineRun.Create(ts.Object, 0, 0, 1); + + Assert.AreEqual( + runWidth + SpecialCharacterTextRun.BoxMargin, + run.GetDistanceFromCharacter(1)); + } + + TextRunProperties CreateDefaultTextProperties() + { + return new TextRunProperties() + { + Typeface = new Typeface("Default"), + FontSize = MockGlyphTypeface.DefaultFontSize, + }; + } + } +}
91
Added unit tests
0
.cs
Tests/Text/TextLineRunTests
mit
AvaloniaUI/AvaloniaEdit
10060805
<NME> TextLineRunTests.cs <BEF> ADDFILE <MSG> Added unit tests <DFF> @@ -0,0 +1,91 @@ +using Avalonia.Media; +using Avalonia.Platform; + +using AvaloniaEdit.AvaloniaMocks; +using AvaloniaEdit.Rendering; + +using Moq; + +using NUnit.Framework; + +using static AvaloniaEdit.Rendering.SingleCharacterElementGenerator; + +namespace AvaloniaEdit.Text +{ + [TestFixture] + internal class TextLineRunTests + { + [Test] + public void Text_Line_Run_Should_Have_Valid_Glyph_Widths() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "0123", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 2); + + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 0, run.GetDistanceFromCharacter(0)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 1, run.GetDistanceFromCharacter(1)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 2, run.GetDistanceFromCharacter(2)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 3, run.GetDistanceFromCharacter(3)); + } + + [Test] + public void Tab_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "\t", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 1); + + Assert.AreEqual(40, run.GetDistanceFromCharacter(1)); + } + + [Test] + public void TextEmbeddedObject_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + int runWidth = 50; + + TextLine textLine = Mock.Of<TextLine>( + t => t.WidthIncludingTrailingWhitespace == runWidth); + + SpecialCharacterTextRun f = new SpecialCharacterTextRun( + new FormattedTextElement("BEL", 1) { TextLine = textLine }, + CreateDefaultTextProperties()); + + Mock<TextSource> ts = new Mock<TextSource>(); + ts.Setup(s=> s.GetTextRun(It.IsAny<int>())).Returns(f); + + TextLineRun run = TextLineRun.Create(ts.Object, 0, 0, 1); + + Assert.AreEqual( + runWidth + SpecialCharacterTextRun.BoxMargin, + run.GetDistanceFromCharacter(1)); + } + + TextRunProperties CreateDefaultTextProperties() + { + return new TextRunProperties() + { + Typeface = new Typeface("Default"), + FontSize = MockGlyphTypeface.DefaultFontSize, + }; + } + } +}
91
Added unit tests
0
.cs
Tests/Text/TextLineRunTests
mit
AvaloniaUI/AvaloniaEdit
10060806
<NME> TextLineRunTests.cs <BEF> ADDFILE <MSG> Added unit tests <DFF> @@ -0,0 +1,91 @@ +using Avalonia.Media; +using Avalonia.Platform; + +using AvaloniaEdit.AvaloniaMocks; +using AvaloniaEdit.Rendering; + +using Moq; + +using NUnit.Framework; + +using static AvaloniaEdit.Rendering.SingleCharacterElementGenerator; + +namespace AvaloniaEdit.Text +{ + [TestFixture] + internal class TextLineRunTests + { + [Test] + public void Text_Line_Run_Should_Have_Valid_Glyph_Widths() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "0123", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 2); + + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 0, run.GetDistanceFromCharacter(0)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 1, run.GetDistanceFromCharacter(1)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 2, run.GetDistanceFromCharacter(2)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 3, run.GetDistanceFromCharacter(3)); + } + + [Test] + public void Tab_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "\t", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 1); + + Assert.AreEqual(40, run.GetDistanceFromCharacter(1)); + } + + [Test] + public void TextEmbeddedObject_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + int runWidth = 50; + + TextLine textLine = Mock.Of<TextLine>( + t => t.WidthIncludingTrailingWhitespace == runWidth); + + SpecialCharacterTextRun f = new SpecialCharacterTextRun( + new FormattedTextElement("BEL", 1) { TextLine = textLine }, + CreateDefaultTextProperties()); + + Mock<TextSource> ts = new Mock<TextSource>(); + ts.Setup(s=> s.GetTextRun(It.IsAny<int>())).Returns(f); + + TextLineRun run = TextLineRun.Create(ts.Object, 0, 0, 1); + + Assert.AreEqual( + runWidth + SpecialCharacterTextRun.BoxMargin, + run.GetDistanceFromCharacter(1)); + } + + TextRunProperties CreateDefaultTextProperties() + { + return new TextRunProperties() + { + Typeface = new Typeface("Default"), + FontSize = MockGlyphTypeface.DefaultFontSize, + }; + } + } +}
91
Added unit tests
0
.cs
Tests/Text/TextLineRunTests
mit
AvaloniaUI/AvaloniaEdit
10060807
<NME> TextLineRunTests.cs <BEF> ADDFILE <MSG> Added unit tests <DFF> @@ -0,0 +1,91 @@ +using Avalonia.Media; +using Avalonia.Platform; + +using AvaloniaEdit.AvaloniaMocks; +using AvaloniaEdit.Rendering; + +using Moq; + +using NUnit.Framework; + +using static AvaloniaEdit.Rendering.SingleCharacterElementGenerator; + +namespace AvaloniaEdit.Text +{ + [TestFixture] + internal class TextLineRunTests + { + [Test] + public void Text_Line_Run_Should_Have_Valid_Glyph_Widths() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "0123", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 2); + + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 0, run.GetDistanceFromCharacter(0)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 1, run.GetDistanceFromCharacter(1)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 2, run.GetDistanceFromCharacter(2)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 3, run.GetDistanceFromCharacter(3)); + } + + [Test] + public void Tab_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "\t", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 1); + + Assert.AreEqual(40, run.GetDistanceFromCharacter(1)); + } + + [Test] + public void TextEmbeddedObject_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + int runWidth = 50; + + TextLine textLine = Mock.Of<TextLine>( + t => t.WidthIncludingTrailingWhitespace == runWidth); + + SpecialCharacterTextRun f = new SpecialCharacterTextRun( + new FormattedTextElement("BEL", 1) { TextLine = textLine }, + CreateDefaultTextProperties()); + + Mock<TextSource> ts = new Mock<TextSource>(); + ts.Setup(s=> s.GetTextRun(It.IsAny<int>())).Returns(f); + + TextLineRun run = TextLineRun.Create(ts.Object, 0, 0, 1); + + Assert.AreEqual( + runWidth + SpecialCharacterTextRun.BoxMargin, + run.GetDistanceFromCharacter(1)); + } + + TextRunProperties CreateDefaultTextProperties() + { + return new TextRunProperties() + { + Typeface = new Typeface("Default"), + FontSize = MockGlyphTypeface.DefaultFontSize, + }; + } + } +}
91
Added unit tests
0
.cs
Tests/Text/TextLineRunTests
mit
AvaloniaUI/AvaloniaEdit
10060808
<NME> TextLineRunTests.cs <BEF> ADDFILE <MSG> Added unit tests <DFF> @@ -0,0 +1,91 @@ +using Avalonia.Media; +using Avalonia.Platform; + +using AvaloniaEdit.AvaloniaMocks; +using AvaloniaEdit.Rendering; + +using Moq; + +using NUnit.Framework; + +using static AvaloniaEdit.Rendering.SingleCharacterElementGenerator; + +namespace AvaloniaEdit.Text +{ + [TestFixture] + internal class TextLineRunTests + { + [Test] + public void Text_Line_Run_Should_Have_Valid_Glyph_Widths() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "0123", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 2); + + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 0, run.GetDistanceFromCharacter(0)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 1, run.GetDistanceFromCharacter(1)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 2, run.GetDistanceFromCharacter(2)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 3, run.GetDistanceFromCharacter(3)); + } + + [Test] + public void Tab_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "\t", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 1); + + Assert.AreEqual(40, run.GetDistanceFromCharacter(1)); + } + + [Test] + public void TextEmbeddedObject_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + int runWidth = 50; + + TextLine textLine = Mock.Of<TextLine>( + t => t.WidthIncludingTrailingWhitespace == runWidth); + + SpecialCharacterTextRun f = new SpecialCharacterTextRun( + new FormattedTextElement("BEL", 1) { TextLine = textLine }, + CreateDefaultTextProperties()); + + Mock<TextSource> ts = new Mock<TextSource>(); + ts.Setup(s=> s.GetTextRun(It.IsAny<int>())).Returns(f); + + TextLineRun run = TextLineRun.Create(ts.Object, 0, 0, 1); + + Assert.AreEqual( + runWidth + SpecialCharacterTextRun.BoxMargin, + run.GetDistanceFromCharacter(1)); + } + + TextRunProperties CreateDefaultTextProperties() + { + return new TextRunProperties() + { + Typeface = new Typeface("Default"), + FontSize = MockGlyphTypeface.DefaultFontSize, + }; + } + } +}
91
Added unit tests
0
.cs
Tests/Text/TextLineRunTests
mit
AvaloniaUI/AvaloniaEdit
10060809
<NME> TextLineRunTests.cs <BEF> ADDFILE <MSG> Added unit tests <DFF> @@ -0,0 +1,91 @@ +using Avalonia.Media; +using Avalonia.Platform; + +using AvaloniaEdit.AvaloniaMocks; +using AvaloniaEdit.Rendering; + +using Moq; + +using NUnit.Framework; + +using static AvaloniaEdit.Rendering.SingleCharacterElementGenerator; + +namespace AvaloniaEdit.Text +{ + [TestFixture] + internal class TextLineRunTests + { + [Test] + public void Text_Line_Run_Should_Have_Valid_Glyph_Widths() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "0123", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 2); + + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 0, run.GetDistanceFromCharacter(0)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 1, run.GetDistanceFromCharacter(1)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 2, run.GetDistanceFromCharacter(2)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 3, run.GetDistanceFromCharacter(3)); + } + + [Test] + public void Tab_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "\t", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 1); + + Assert.AreEqual(40, run.GetDistanceFromCharacter(1)); + } + + [Test] + public void TextEmbeddedObject_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + int runWidth = 50; + + TextLine textLine = Mock.Of<TextLine>( + t => t.WidthIncludingTrailingWhitespace == runWidth); + + SpecialCharacterTextRun f = new SpecialCharacterTextRun( + new FormattedTextElement("BEL", 1) { TextLine = textLine }, + CreateDefaultTextProperties()); + + Mock<TextSource> ts = new Mock<TextSource>(); + ts.Setup(s=> s.GetTextRun(It.IsAny<int>())).Returns(f); + + TextLineRun run = TextLineRun.Create(ts.Object, 0, 0, 1); + + Assert.AreEqual( + runWidth + SpecialCharacterTextRun.BoxMargin, + run.GetDistanceFromCharacter(1)); + } + + TextRunProperties CreateDefaultTextProperties() + { + return new TextRunProperties() + { + Typeface = new Typeface("Default"), + FontSize = MockGlyphTypeface.DefaultFontSize, + }; + } + } +}
91
Added unit tests
0
.cs
Tests/Text/TextLineRunTests
mit
AvaloniaUI/AvaloniaEdit
10060810
<NME> TextLineRunTests.cs <BEF> ADDFILE <MSG> Added unit tests <DFF> @@ -0,0 +1,91 @@ +using Avalonia.Media; +using Avalonia.Platform; + +using AvaloniaEdit.AvaloniaMocks; +using AvaloniaEdit.Rendering; + +using Moq; + +using NUnit.Framework; + +using static AvaloniaEdit.Rendering.SingleCharacterElementGenerator; + +namespace AvaloniaEdit.Text +{ + [TestFixture] + internal class TextLineRunTests + { + [Test] + public void Text_Line_Run_Should_Have_Valid_Glyph_Widths() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "0123", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 2); + + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 0, run.GetDistanceFromCharacter(0)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 1, run.GetDistanceFromCharacter(1)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 2, run.GetDistanceFromCharacter(2)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 3, run.GetDistanceFromCharacter(3)); + } + + [Test] + public void Tab_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "\t", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 1); + + Assert.AreEqual(40, run.GetDistanceFromCharacter(1)); + } + + [Test] + public void TextEmbeddedObject_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + int runWidth = 50; + + TextLine textLine = Mock.Of<TextLine>( + t => t.WidthIncludingTrailingWhitespace == runWidth); + + SpecialCharacterTextRun f = new SpecialCharacterTextRun( + new FormattedTextElement("BEL", 1) { TextLine = textLine }, + CreateDefaultTextProperties()); + + Mock<TextSource> ts = new Mock<TextSource>(); + ts.Setup(s=> s.GetTextRun(It.IsAny<int>())).Returns(f); + + TextLineRun run = TextLineRun.Create(ts.Object, 0, 0, 1); + + Assert.AreEqual( + runWidth + SpecialCharacterTextRun.BoxMargin, + run.GetDistanceFromCharacter(1)); + } + + TextRunProperties CreateDefaultTextProperties() + { + return new TextRunProperties() + { + Typeface = new Typeface("Default"), + FontSize = MockGlyphTypeface.DefaultFontSize, + }; + } + } +}
91
Added unit tests
0
.cs
Tests/Text/TextLineRunTests
mit
AvaloniaUI/AvaloniaEdit
10060811
<NME> TextLineRunTests.cs <BEF> ADDFILE <MSG> Added unit tests <DFF> @@ -0,0 +1,91 @@ +using Avalonia.Media; +using Avalonia.Platform; + +using AvaloniaEdit.AvaloniaMocks; +using AvaloniaEdit.Rendering; + +using Moq; + +using NUnit.Framework; + +using static AvaloniaEdit.Rendering.SingleCharacterElementGenerator; + +namespace AvaloniaEdit.Text +{ + [TestFixture] + internal class TextLineRunTests + { + [Test] + public void Text_Line_Run_Should_Have_Valid_Glyph_Widths() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "0123", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 2); + + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 0, run.GetDistanceFromCharacter(0)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 1, run.GetDistanceFromCharacter(1)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 2, run.GetDistanceFromCharacter(2)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 3, run.GetDistanceFromCharacter(3)); + } + + [Test] + public void Tab_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "\t", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 1); + + Assert.AreEqual(40, run.GetDistanceFromCharacter(1)); + } + + [Test] + public void TextEmbeddedObject_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + int runWidth = 50; + + TextLine textLine = Mock.Of<TextLine>( + t => t.WidthIncludingTrailingWhitespace == runWidth); + + SpecialCharacterTextRun f = new SpecialCharacterTextRun( + new FormattedTextElement("BEL", 1) { TextLine = textLine }, + CreateDefaultTextProperties()); + + Mock<TextSource> ts = new Mock<TextSource>(); + ts.Setup(s=> s.GetTextRun(It.IsAny<int>())).Returns(f); + + TextLineRun run = TextLineRun.Create(ts.Object, 0, 0, 1); + + Assert.AreEqual( + runWidth + SpecialCharacterTextRun.BoxMargin, + run.GetDistanceFromCharacter(1)); + } + + TextRunProperties CreateDefaultTextProperties() + { + return new TextRunProperties() + { + Typeface = new Typeface("Default"), + FontSize = MockGlyphTypeface.DefaultFontSize, + }; + } + } +}
91
Added unit tests
0
.cs
Tests/Text/TextLineRunTests
mit
AvaloniaUI/AvaloniaEdit
10060812
<NME> TextLineRunTests.cs <BEF> ADDFILE <MSG> Added unit tests <DFF> @@ -0,0 +1,91 @@ +using Avalonia.Media; +using Avalonia.Platform; + +using AvaloniaEdit.AvaloniaMocks; +using AvaloniaEdit.Rendering; + +using Moq; + +using NUnit.Framework; + +using static AvaloniaEdit.Rendering.SingleCharacterElementGenerator; + +namespace AvaloniaEdit.Text +{ + [TestFixture] + internal class TextLineRunTests + { + [Test] + public void Text_Line_Run_Should_Have_Valid_Glyph_Widths() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "0123", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 2); + + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 0, run.GetDistanceFromCharacter(0)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 1, run.GetDistanceFromCharacter(1)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 2, run.GetDistanceFromCharacter(2)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 3, run.GetDistanceFromCharacter(3)); + } + + [Test] + public void Tab_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "\t", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 1); + + Assert.AreEqual(40, run.GetDistanceFromCharacter(1)); + } + + [Test] + public void TextEmbeddedObject_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + int runWidth = 50; + + TextLine textLine = Mock.Of<TextLine>( + t => t.WidthIncludingTrailingWhitespace == runWidth); + + SpecialCharacterTextRun f = new SpecialCharacterTextRun( + new FormattedTextElement("BEL", 1) { TextLine = textLine }, + CreateDefaultTextProperties()); + + Mock<TextSource> ts = new Mock<TextSource>(); + ts.Setup(s=> s.GetTextRun(It.IsAny<int>())).Returns(f); + + TextLineRun run = TextLineRun.Create(ts.Object, 0, 0, 1); + + Assert.AreEqual( + runWidth + SpecialCharacterTextRun.BoxMargin, + run.GetDistanceFromCharacter(1)); + } + + TextRunProperties CreateDefaultTextProperties() + { + return new TextRunProperties() + { + Typeface = new Typeface("Default"), + FontSize = MockGlyphTypeface.DefaultFontSize, + }; + } + } +}
91
Added unit tests
0
.cs
Tests/Text/TextLineRunTests
mit
AvaloniaUI/AvaloniaEdit
10060813
<NME> TextLineRunTests.cs <BEF> ADDFILE <MSG> Added unit tests <DFF> @@ -0,0 +1,91 @@ +using Avalonia.Media; +using Avalonia.Platform; + +using AvaloniaEdit.AvaloniaMocks; +using AvaloniaEdit.Rendering; + +using Moq; + +using NUnit.Framework; + +using static AvaloniaEdit.Rendering.SingleCharacterElementGenerator; + +namespace AvaloniaEdit.Text +{ + [TestFixture] + internal class TextLineRunTests + { + [Test] + public void Text_Line_Run_Should_Have_Valid_Glyph_Widths() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "0123", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 2); + + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 0, run.GetDistanceFromCharacter(0)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 1, run.GetDistanceFromCharacter(1)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 2, run.GetDistanceFromCharacter(2)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 3, run.GetDistanceFromCharacter(3)); + } + + [Test] + public void Tab_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "\t", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 1); + + Assert.AreEqual(40, run.GetDistanceFromCharacter(1)); + } + + [Test] + public void TextEmbeddedObject_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + int runWidth = 50; + + TextLine textLine = Mock.Of<TextLine>( + t => t.WidthIncludingTrailingWhitespace == runWidth); + + SpecialCharacterTextRun f = new SpecialCharacterTextRun( + new FormattedTextElement("BEL", 1) { TextLine = textLine }, + CreateDefaultTextProperties()); + + Mock<TextSource> ts = new Mock<TextSource>(); + ts.Setup(s=> s.GetTextRun(It.IsAny<int>())).Returns(f); + + TextLineRun run = TextLineRun.Create(ts.Object, 0, 0, 1); + + Assert.AreEqual( + runWidth + SpecialCharacterTextRun.BoxMargin, + run.GetDistanceFromCharacter(1)); + } + + TextRunProperties CreateDefaultTextProperties() + { + return new TextRunProperties() + { + Typeface = new Typeface("Default"), + FontSize = MockGlyphTypeface.DefaultFontSize, + }; + } + } +}
91
Added unit tests
0
.cs
Tests/Text/TextLineRunTests
mit
AvaloniaUI/AvaloniaEdit
10060814
<NME> TextLineRunTests.cs <BEF> ADDFILE <MSG> Added unit tests <DFF> @@ -0,0 +1,91 @@ +using Avalonia.Media; +using Avalonia.Platform; + +using AvaloniaEdit.AvaloniaMocks; +using AvaloniaEdit.Rendering; + +using Moq; + +using NUnit.Framework; + +using static AvaloniaEdit.Rendering.SingleCharacterElementGenerator; + +namespace AvaloniaEdit.Text +{ + [TestFixture] + internal class TextLineRunTests + { + [Test] + public void Text_Line_Run_Should_Have_Valid_Glyph_Widths() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "0123", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 2); + + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 0, run.GetDistanceFromCharacter(0)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 1, run.GetDistanceFromCharacter(1)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 2, run.GetDistanceFromCharacter(2)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 3, run.GetDistanceFromCharacter(3)); + } + + [Test] + public void Tab_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "\t", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 1); + + Assert.AreEqual(40, run.GetDistanceFromCharacter(1)); + } + + [Test] + public void TextEmbeddedObject_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + int runWidth = 50; + + TextLine textLine = Mock.Of<TextLine>( + t => t.WidthIncludingTrailingWhitespace == runWidth); + + SpecialCharacterTextRun f = new SpecialCharacterTextRun( + new FormattedTextElement("BEL", 1) { TextLine = textLine }, + CreateDefaultTextProperties()); + + Mock<TextSource> ts = new Mock<TextSource>(); + ts.Setup(s=> s.GetTextRun(It.IsAny<int>())).Returns(f); + + TextLineRun run = TextLineRun.Create(ts.Object, 0, 0, 1); + + Assert.AreEqual( + runWidth + SpecialCharacterTextRun.BoxMargin, + run.GetDistanceFromCharacter(1)); + } + + TextRunProperties CreateDefaultTextProperties() + { + return new TextRunProperties() + { + Typeface = new Typeface("Default"), + FontSize = MockGlyphTypeface.DefaultFontSize, + }; + } + } +}
91
Added unit tests
0
.cs
Tests/Text/TextLineRunTests
mit
AvaloniaUI/AvaloniaEdit
10060815
<NME> TextLineRunTests.cs <BEF> ADDFILE <MSG> Added unit tests <DFF> @@ -0,0 +1,91 @@ +using Avalonia.Media; +using Avalonia.Platform; + +using AvaloniaEdit.AvaloniaMocks; +using AvaloniaEdit.Rendering; + +using Moq; + +using NUnit.Framework; + +using static AvaloniaEdit.Rendering.SingleCharacterElementGenerator; + +namespace AvaloniaEdit.Text +{ + [TestFixture] + internal class TextLineRunTests + { + [Test] + public void Text_Line_Run_Should_Have_Valid_Glyph_Widths() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "0123", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 2); + + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 0, run.GetDistanceFromCharacter(0)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 1, run.GetDistanceFromCharacter(1)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 2, run.GetDistanceFromCharacter(2)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 3, run.GetDistanceFromCharacter(3)); + } + + [Test] + public void Tab_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "\t", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 1); + + Assert.AreEqual(40, run.GetDistanceFromCharacter(1)); + } + + [Test] + public void TextEmbeddedObject_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + int runWidth = 50; + + TextLine textLine = Mock.Of<TextLine>( + t => t.WidthIncludingTrailingWhitespace == runWidth); + + SpecialCharacterTextRun f = new SpecialCharacterTextRun( + new FormattedTextElement("BEL", 1) { TextLine = textLine }, + CreateDefaultTextProperties()); + + Mock<TextSource> ts = new Mock<TextSource>(); + ts.Setup(s=> s.GetTextRun(It.IsAny<int>())).Returns(f); + + TextLineRun run = TextLineRun.Create(ts.Object, 0, 0, 1); + + Assert.AreEqual( + runWidth + SpecialCharacterTextRun.BoxMargin, + run.GetDistanceFromCharacter(1)); + } + + TextRunProperties CreateDefaultTextProperties() + { + return new TextRunProperties() + { + Typeface = new Typeface("Default"), + FontSize = MockGlyphTypeface.DefaultFontSize, + }; + } + } +}
91
Added unit tests
0
.cs
Tests/Text/TextLineRunTests
mit
AvaloniaUI/AvaloniaEdit
10060816
<NME> TextLineRunTests.cs <BEF> ADDFILE <MSG> Added unit tests <DFF> @@ -0,0 +1,91 @@ +using Avalonia.Media; +using Avalonia.Platform; + +using AvaloniaEdit.AvaloniaMocks; +using AvaloniaEdit.Rendering; + +using Moq; + +using NUnit.Framework; + +using static AvaloniaEdit.Rendering.SingleCharacterElementGenerator; + +namespace AvaloniaEdit.Text +{ + [TestFixture] + internal class TextLineRunTests + { + [Test] + public void Text_Line_Run_Should_Have_Valid_Glyph_Widths() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "0123", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 2); + + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 0, run.GetDistanceFromCharacter(0)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 1, run.GetDistanceFromCharacter(1)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 2, run.GetDistanceFromCharacter(2)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 3, run.GetDistanceFromCharacter(3)); + } + + [Test] + public void Tab_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "\t", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 1); + + Assert.AreEqual(40, run.GetDistanceFromCharacter(1)); + } + + [Test] + public void TextEmbeddedObject_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + int runWidth = 50; + + TextLine textLine = Mock.Of<TextLine>( + t => t.WidthIncludingTrailingWhitespace == runWidth); + + SpecialCharacterTextRun f = new SpecialCharacterTextRun( + new FormattedTextElement("BEL", 1) { TextLine = textLine }, + CreateDefaultTextProperties()); + + Mock<TextSource> ts = new Mock<TextSource>(); + ts.Setup(s=> s.GetTextRun(It.IsAny<int>())).Returns(f); + + TextLineRun run = TextLineRun.Create(ts.Object, 0, 0, 1); + + Assert.AreEqual( + runWidth + SpecialCharacterTextRun.BoxMargin, + run.GetDistanceFromCharacter(1)); + } + + TextRunProperties CreateDefaultTextProperties() + { + return new TextRunProperties() + { + Typeface = new Typeface("Default"), + FontSize = MockGlyphTypeface.DefaultFontSize, + }; + } + } +}
91
Added unit tests
0
.cs
Tests/Text/TextLineRunTests
mit
AvaloniaUI/AvaloniaEdit
10060817
<NME> TextLineRunTests.cs <BEF> ADDFILE <MSG> Added unit tests <DFF> @@ -0,0 +1,91 @@ +using Avalonia.Media; +using Avalonia.Platform; + +using AvaloniaEdit.AvaloniaMocks; +using AvaloniaEdit.Rendering; + +using Moq; + +using NUnit.Framework; + +using static AvaloniaEdit.Rendering.SingleCharacterElementGenerator; + +namespace AvaloniaEdit.Text +{ + [TestFixture] + internal class TextLineRunTests + { + [Test] + public void Text_Line_Run_Should_Have_Valid_Glyph_Widths() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "0123", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 2); + + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 0, run.GetDistanceFromCharacter(0)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 1, run.GetDistanceFromCharacter(1)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 2, run.GetDistanceFromCharacter(2)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 3, run.GetDistanceFromCharacter(3)); + } + + [Test] + public void Tab_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "\t", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 1); + + Assert.AreEqual(40, run.GetDistanceFromCharacter(1)); + } + + [Test] + public void TextEmbeddedObject_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + int runWidth = 50; + + TextLine textLine = Mock.Of<TextLine>( + t => t.WidthIncludingTrailingWhitespace == runWidth); + + SpecialCharacterTextRun f = new SpecialCharacterTextRun( + new FormattedTextElement("BEL", 1) { TextLine = textLine }, + CreateDefaultTextProperties()); + + Mock<TextSource> ts = new Mock<TextSource>(); + ts.Setup(s=> s.GetTextRun(It.IsAny<int>())).Returns(f); + + TextLineRun run = TextLineRun.Create(ts.Object, 0, 0, 1); + + Assert.AreEqual( + runWidth + SpecialCharacterTextRun.BoxMargin, + run.GetDistanceFromCharacter(1)); + } + + TextRunProperties CreateDefaultTextProperties() + { + return new TextRunProperties() + { + Typeface = new Typeface("Default"), + FontSize = MockGlyphTypeface.DefaultFontSize, + }; + } + } +}
91
Added unit tests
0
.cs
Tests/Text/TextLineRunTests
mit
AvaloniaUI/AvaloniaEdit
10060818
<NME> TextLineRunTests.cs <BEF> ADDFILE <MSG> Added unit tests <DFF> @@ -0,0 +1,91 @@ +using Avalonia.Media; +using Avalonia.Platform; + +using AvaloniaEdit.AvaloniaMocks; +using AvaloniaEdit.Rendering; + +using Moq; + +using NUnit.Framework; + +using static AvaloniaEdit.Rendering.SingleCharacterElementGenerator; + +namespace AvaloniaEdit.Text +{ + [TestFixture] + internal class TextLineRunTests + { + [Test] + public void Text_Line_Run_Should_Have_Valid_Glyph_Widths() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "0123", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 2); + + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 0, run.GetDistanceFromCharacter(0)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 1, run.GetDistanceFromCharacter(1)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 2, run.GetDistanceFromCharacter(2)); + Assert.AreEqual(MockGlyphTypeface.GlyphAdvance * 3, run.GetDistanceFromCharacter(3)); + } + + [Test] + public void Tab_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + SimpleTextSource s = new SimpleTextSource( + "\t", + CreateDefaultTextProperties()); + + TextLineRun run = TextLineRun.Create(s, 0, 0, 1); + + Assert.AreEqual(40, run.GetDistanceFromCharacter(1)); + } + + [Test] + public void TextEmbeddedObject_Line_Run_Should_Have_Fixed_Glyph_Width() + { + using var app = UnitTestApplication.Start(new TestServices().With( + renderInterface: new MockPlatformRenderInterface(), + fontManagerImpl: new MockFontManagerImpl(), + formattedTextImpl: Mock.Of<IFormattedTextImpl>())); + + int runWidth = 50; + + TextLine textLine = Mock.Of<TextLine>( + t => t.WidthIncludingTrailingWhitespace == runWidth); + + SpecialCharacterTextRun f = new SpecialCharacterTextRun( + new FormattedTextElement("BEL", 1) { TextLine = textLine }, + CreateDefaultTextProperties()); + + Mock<TextSource> ts = new Mock<TextSource>(); + ts.Setup(s=> s.GetTextRun(It.IsAny<int>())).Returns(f); + + TextLineRun run = TextLineRun.Create(ts.Object, 0, 0, 1); + + Assert.AreEqual( + runWidth + SpecialCharacterTextRun.BoxMargin, + run.GetDistanceFromCharacter(1)); + } + + TextRunProperties CreateDefaultTextProperties() + { + return new TextRunProperties() + { + Typeface = new Typeface("Default"), + FontSize = MockGlyphTypeface.DefaultFontSize, + }; + } + } +}
91
Added unit tests
0
.cs
Tests/Text/TextLineRunTests
mit
AvaloniaUI/AvaloniaEdit
10060819
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text Fixed index out of range replacing text <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10060820
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text Fixed index out of range replacing text <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10060821
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text Fixed index out of range replacing text <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10060822
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text Fixed index out of range replacing text <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10060823
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text Fixed index out of range replacing text <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10060824
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text Fixed index out of range replacing text <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10060825
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text Fixed index out of range replacing text <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10060826
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text Fixed index out of range replacing text <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10060827
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text Fixed index out of range replacing text <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10060828
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text Fixed index out of range replacing text <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10060829
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text Fixed index out of range replacing text <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10060830
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text Fixed index out of range replacing text <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10060831
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text Fixed index out of range replacing text <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10060832
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text Fixed index out of range replacing text <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10060833
<NME> DocumentSnapshotTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class DocumentSnapshotTests { [Test] public void DocumentSnaphot_Should_Have_CorrectLineText() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy", documentSnaphot.GetLineText(0)); Assert.AreEqual("pussy", documentSnaphot.GetLineText(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineText(2)); } [Test] public void DocumentSnaphot_Should_Have_CorrectLineText_Including_Terminator() { TextDocument document = new TextDocument(); document.Text = "puppy\npussy\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Text_Including_Terminator_CR_LF() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("puppy\r\n", documentSnaphot.GetLineTextIncludingTerminator(0)); Assert.AreEqual("pussy\r\n", documentSnaphot.GetLineTextIncludingTerminator(1)); Assert.AreEqual("birdie", documentSnaphot.GetLineTextIncludingTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Terminators() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(0)); Assert.AreEqual("\r\n", documentSnaphot.GetLineTerminator(1)); Assert.AreEqual("", documentSnaphot.GetLineTerminator(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(5, documentSnaphot.GetLineLength(0)); Assert.AreEqual(5, documentSnaphot.GetLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetLineLength(2)); } [Test] public void DocumentSnaphot_Should_Have_Correct_Line_Total_Len() { TextDocument document = new TextDocument(); document.Text = "puppy\r\npussy\r\nbirdie"; DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(0)); Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } } } <MSG> Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text Fixed index out of range replacing text <DFF> @@ -85,5 +85,57 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual(7, documentSnaphot.GetTotalLineLength(1)); Assert.AreEqual(6, documentSnaphot.GetTotalLineLength(2)); } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_All_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 3); + + Assert.AreEqual(0, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_First_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 0); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Two_First_Lines() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(0, 1); + + Assert.AreEqual(2, documentSnaphot.LineCount); + } + + [Test] + public void DocumentSnapshot_Should_Have_Correct_Line_Count_Before_Remove_Last_Line() + { + TextDocument document = new TextDocument(); + document.Text = "puppy\r\npussy\r\nbirdie\r\ndoggie"; + + DocumentSnapshot documentSnaphot = new DocumentSnapshot(document); + + documentSnaphot.RemoveLines(3, 3); + + Assert.AreEqual(3, documentSnaphot.LineCount); + } } }
52
Merge pull request #214 from AvaloniaUI/index-out-of-range-replacing-text
0
.cs
Tests/TextMate/DocumentSnapshotTests
mit
AvaloniaUI/AvaloniaEdit
10060834
<NME> PopupWithCustomPosition.cs <BEF> using Avalonia; using Avalonia.Controls.Primitives; namespace AvaloniaEdit.CodeCompletion { internal class PopupWithCustomPosition : Popup { public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); public Point Position { get; set; } protected override Point GetPosition() { return Position; } set { HorizontalOffset = value.X; VerticalOffset = value.Y; //this.Revalidate(VerticalOffsetProperty); } } } } <MSG> update to be compatible with new avalonia api for pixelpoint <DFF> @@ -8,9 +8,9 @@ namespace AvaloniaEdit.CodeCompletion public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); - public Point Position { get; set; } + public PixelPoint Position { get; set; } - protected override Point GetPosition() + protected override PixelPoint GetPosition() { return Position; }
2
update to be compatible with new avalonia api for pixelpoint
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060835
<NME> PopupWithCustomPosition.cs <BEF> using Avalonia; using Avalonia.Controls.Primitives; namespace AvaloniaEdit.CodeCompletion { internal class PopupWithCustomPosition : Popup { public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); public Point Position { get; set; } protected override Point GetPosition() { return Position; } set { HorizontalOffset = value.X; VerticalOffset = value.Y; //this.Revalidate(VerticalOffsetProperty); } } } } <MSG> update to be compatible with new avalonia api for pixelpoint <DFF> @@ -8,9 +8,9 @@ namespace AvaloniaEdit.CodeCompletion public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); - public Point Position { get; set; } + public PixelPoint Position { get; set; } - protected override Point GetPosition() + protected override PixelPoint GetPosition() { return Position; }
2
update to be compatible with new avalonia api for pixelpoint
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060836
<NME> PopupWithCustomPosition.cs <BEF> using Avalonia; using Avalonia.Controls.Primitives; namespace AvaloniaEdit.CodeCompletion { internal class PopupWithCustomPosition : Popup { public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); public Point Position { get; set; } protected override Point GetPosition() { return Position; } set { HorizontalOffset = value.X; VerticalOffset = value.Y; //this.Revalidate(VerticalOffsetProperty); } } } } <MSG> update to be compatible with new avalonia api for pixelpoint <DFF> @@ -8,9 +8,9 @@ namespace AvaloniaEdit.CodeCompletion public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); - public Point Position { get; set; } + public PixelPoint Position { get; set; } - protected override Point GetPosition() + protected override PixelPoint GetPosition() { return Position; }
2
update to be compatible with new avalonia api for pixelpoint
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060837
<NME> PopupWithCustomPosition.cs <BEF> using Avalonia; using Avalonia.Controls.Primitives; namespace AvaloniaEdit.CodeCompletion { internal class PopupWithCustomPosition : Popup { public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); public Point Position { get; set; } protected override Point GetPosition() { return Position; } set { HorizontalOffset = value.X; VerticalOffset = value.Y; //this.Revalidate(VerticalOffsetProperty); } } } } <MSG> update to be compatible with new avalonia api for pixelpoint <DFF> @@ -8,9 +8,9 @@ namespace AvaloniaEdit.CodeCompletion public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); - public Point Position { get; set; } + public PixelPoint Position { get; set; } - protected override Point GetPosition() + protected override PixelPoint GetPosition() { return Position; }
2
update to be compatible with new avalonia api for pixelpoint
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060838
<NME> PopupWithCustomPosition.cs <BEF> using Avalonia; using Avalonia.Controls.Primitives; namespace AvaloniaEdit.CodeCompletion { internal class PopupWithCustomPosition : Popup { public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); public Point Position { get; set; } protected override Point GetPosition() { return Position; } set { HorizontalOffset = value.X; VerticalOffset = value.Y; //this.Revalidate(VerticalOffsetProperty); } } } } <MSG> update to be compatible with new avalonia api for pixelpoint <DFF> @@ -8,9 +8,9 @@ namespace AvaloniaEdit.CodeCompletion public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); - public Point Position { get; set; } + public PixelPoint Position { get; set; } - protected override Point GetPosition() + protected override PixelPoint GetPosition() { return Position; }
2
update to be compatible with new avalonia api for pixelpoint
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060839
<NME> PopupWithCustomPosition.cs <BEF> using Avalonia; using Avalonia.Controls.Primitives; namespace AvaloniaEdit.CodeCompletion { internal class PopupWithCustomPosition : Popup { public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); public Point Position { get; set; } protected override Point GetPosition() { return Position; } set { HorizontalOffset = value.X; VerticalOffset = value.Y; //this.Revalidate(VerticalOffsetProperty); } } } } <MSG> update to be compatible with new avalonia api for pixelpoint <DFF> @@ -8,9 +8,9 @@ namespace AvaloniaEdit.CodeCompletion public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); - public Point Position { get; set; } + public PixelPoint Position { get; set; } - protected override Point GetPosition() + protected override PixelPoint GetPosition() { return Position; }
2
update to be compatible with new avalonia api for pixelpoint
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060840
<NME> PopupWithCustomPosition.cs <BEF> using Avalonia; using Avalonia.Controls.Primitives; namespace AvaloniaEdit.CodeCompletion { internal class PopupWithCustomPosition : Popup { public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); public Point Position { get; set; } protected override Point GetPosition() { return Position; } set { HorizontalOffset = value.X; VerticalOffset = value.Y; //this.Revalidate(VerticalOffsetProperty); } } } } <MSG> update to be compatible with new avalonia api for pixelpoint <DFF> @@ -8,9 +8,9 @@ namespace AvaloniaEdit.CodeCompletion public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); - public Point Position { get; set; } + public PixelPoint Position { get; set; } - protected override Point GetPosition() + protected override PixelPoint GetPosition() { return Position; }
2
update to be compatible with new avalonia api for pixelpoint
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060841
<NME> PopupWithCustomPosition.cs <BEF> using Avalonia; using Avalonia.Controls.Primitives; namespace AvaloniaEdit.CodeCompletion { internal class PopupWithCustomPosition : Popup { public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); public Point Position { get; set; } protected override Point GetPosition() { return Position; } set { HorizontalOffset = value.X; VerticalOffset = value.Y; //this.Revalidate(VerticalOffsetProperty); } } } } <MSG> update to be compatible with new avalonia api for pixelpoint <DFF> @@ -8,9 +8,9 @@ namespace AvaloniaEdit.CodeCompletion public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); - public Point Position { get; set; } + public PixelPoint Position { get; set; } - protected override Point GetPosition() + protected override PixelPoint GetPosition() { return Position; }
2
update to be compatible with new avalonia api for pixelpoint
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060842
<NME> PopupWithCustomPosition.cs <BEF> using Avalonia; using Avalonia.Controls.Primitives; namespace AvaloniaEdit.CodeCompletion { internal class PopupWithCustomPosition : Popup { public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); public Point Position { get; set; } protected override Point GetPosition() { return Position; } set { HorizontalOffset = value.X; VerticalOffset = value.Y; //this.Revalidate(VerticalOffsetProperty); } } } } <MSG> update to be compatible with new avalonia api for pixelpoint <DFF> @@ -8,9 +8,9 @@ namespace AvaloniaEdit.CodeCompletion public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); - public Point Position { get; set; } + public PixelPoint Position { get; set; } - protected override Point GetPosition() + protected override PixelPoint GetPosition() { return Position; }
2
update to be compatible with new avalonia api for pixelpoint
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060843
<NME> PopupWithCustomPosition.cs <BEF> using Avalonia; using Avalonia.Controls.Primitives; namespace AvaloniaEdit.CodeCompletion { internal class PopupWithCustomPosition : Popup { public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); public Point Position { get; set; } protected override Point GetPosition() { return Position; } set { HorizontalOffset = value.X; VerticalOffset = value.Y; //this.Revalidate(VerticalOffsetProperty); } } } } <MSG> update to be compatible with new avalonia api for pixelpoint <DFF> @@ -8,9 +8,9 @@ namespace AvaloniaEdit.CodeCompletion public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); - public Point Position { get; set; } + public PixelPoint Position { get; set; } - protected override Point GetPosition() + protected override PixelPoint GetPosition() { return Position; }
2
update to be compatible with new avalonia api for pixelpoint
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060844
<NME> PopupWithCustomPosition.cs <BEF> using Avalonia; using Avalonia.Controls.Primitives; namespace AvaloniaEdit.CodeCompletion { internal class PopupWithCustomPosition : Popup { public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); public Point Position { get; set; } protected override Point GetPosition() { return Position; } set { HorizontalOffset = value.X; VerticalOffset = value.Y; //this.Revalidate(VerticalOffsetProperty); } } } } <MSG> update to be compatible with new avalonia api for pixelpoint <DFF> @@ -8,9 +8,9 @@ namespace AvaloniaEdit.CodeCompletion public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); - public Point Position { get; set; } + public PixelPoint Position { get; set; } - protected override Point GetPosition() + protected override PixelPoint GetPosition() { return Position; }
2
update to be compatible with new avalonia api for pixelpoint
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060845
<NME> PopupWithCustomPosition.cs <BEF> using Avalonia; using Avalonia.Controls.Primitives; namespace AvaloniaEdit.CodeCompletion { internal class PopupWithCustomPosition : Popup { public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); public Point Position { get; set; } protected override Point GetPosition() { return Position; } set { HorizontalOffset = value.X; VerticalOffset = value.Y; //this.Revalidate(VerticalOffsetProperty); } } } } <MSG> update to be compatible with new avalonia api for pixelpoint <DFF> @@ -8,9 +8,9 @@ namespace AvaloniaEdit.CodeCompletion public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); - public Point Position { get; set; } + public PixelPoint Position { get; set; } - protected override Point GetPosition() + protected override PixelPoint GetPosition() { return Position; }
2
update to be compatible with new avalonia api for pixelpoint
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060846
<NME> PopupWithCustomPosition.cs <BEF> using Avalonia; using Avalonia.Controls.Primitives; namespace AvaloniaEdit.CodeCompletion { internal class PopupWithCustomPosition : Popup { public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); public Point Position { get; set; } protected override Point GetPosition() { return Position; } set { HorizontalOffset = value.X; VerticalOffset = value.Y; //this.Revalidate(VerticalOffsetProperty); } } } } <MSG> update to be compatible with new avalonia api for pixelpoint <DFF> @@ -8,9 +8,9 @@ namespace AvaloniaEdit.CodeCompletion public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); - public Point Position { get; set; } + public PixelPoint Position { get; set; } - protected override Point GetPosition() + protected override PixelPoint GetPosition() { return Position; }
2
update to be compatible with new avalonia api for pixelpoint
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060847
<NME> PopupWithCustomPosition.cs <BEF> using Avalonia; using Avalonia.Controls.Primitives; namespace AvaloniaEdit.CodeCompletion { internal class PopupWithCustomPosition : Popup { public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); public Point Position { get; set; } protected override Point GetPosition() { return Position; } set { HorizontalOffset = value.X; VerticalOffset = value.Y; //this.Revalidate(VerticalOffsetProperty); } } } } <MSG> update to be compatible with new avalonia api for pixelpoint <DFF> @@ -8,9 +8,9 @@ namespace AvaloniaEdit.CodeCompletion public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); - public Point Position { get; set; } + public PixelPoint Position { get; set; } - protected override Point GetPosition() + protected override PixelPoint GetPosition() { return Position; }
2
update to be compatible with new avalonia api for pixelpoint
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060848
<NME> PopupWithCustomPosition.cs <BEF> using Avalonia; using Avalonia.Controls.Primitives; namespace AvaloniaEdit.CodeCompletion { internal class PopupWithCustomPosition : Popup { public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); public Point Position { get; set; } protected override Point GetPosition() { return Position; } set { HorizontalOffset = value.X; VerticalOffset = value.Y; //this.Revalidate(VerticalOffsetProperty); } } } } <MSG> update to be compatible with new avalonia api for pixelpoint <DFF> @@ -8,9 +8,9 @@ namespace AvaloniaEdit.CodeCompletion public static readonly AvaloniaProperty<Point> PositionProperty = AvaloniaProperty.Register<PopupWithCustomPosition, Point>(nameof(Position)); - public Point Position { get; set; } + public PixelPoint Position { get; set; } - protected override Point GetPosition() + protected override PixelPoint GetPosition() { return Position; }
2
update to be compatible with new avalonia api for pixelpoint
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10060849
<NME> tests.js <BEF> /** * loadjs tests * @module test/tests.js */ var pathsLoaded = null, // file register testEl = null, expect = chai.expect; describe('hello', function() { beforeEach(function() { // reset register pathsLoaded = {}; // reset loadjs dependencies loadjs.reset(); }); // ========================================================================== // JavaScript file loading tests }); }); it('should call success callback on two valid paths', function(done) { loadjs(['assets/file1.js', 'assets/file2.js'], function() { assert.equal(pathsLoaded['file1.js'], true); error: function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); } }); }); it('should call before callback before embedding into document', function(done) { var scriptTags = []; loadjs(['assets/file1.js', 'assets/file2.js'], { before: function(path, el) { scriptTags.push({ path: path, el: el }); // add cross origin script for file2 if (path === 'assets/file2.js') { el.crossOrigin = 'anonymous'; } }, success: function() { assert.equal(scriptTags[0].path, 'assets/file1.js'); assert.equal(scriptTags[1].path, 'assets/file2.js'); assert.equal(scriptTags[0].el.crossOrigin, undefined); assert.equal(scriptTags[1].el.crossOrigin, 'anonymous'); it('should throw an error if bundle is already defined', function() { loadjs(['assets/file1.js'], 'bundle3'); var fn = function() { loadjs(['assets/file1.js'], 'bundle3'); }; document.body.appendChild(el); }); it('should call fail callback on invalid path', function(done) { loadjs(['assets/file-doesntexist.js'], function() {throw "Executed success callback";}, function() {done();}); }); }); async: false }); }; // run tests testFn(paths); }); it('should support multiple tries', function(done) { loadjs('assets/file-numretries.js', { error: function() { // check number of scripts in document var selector = 'script[src="assets/file-numretries.js"]', scripts = document.querySelectorAll(selector); if (scripts.length === 2) done(); }, numRetries: 1 }); }); // Un-'x' this for testing ad blocked scripts. // Ghostery: Disallow "Google Adservices" // AdBlock Plus: Add "www.googletagservices.com/tag/js/gpt.js" as a // custom filter under Options // xit('it should report ad blocked scripts as missing', function(done) { var s1 = 'https://www.googletagservices.com/tag/js/gpt.js', s2 = 'https://munchkin.marketo.net/munchkin-beta.js'; loadjs([s1, s2, 'assets/file1.js'], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsNotFound.length, 2); assert.equal(pathsNotFound[0], s1); assert.equal(pathsNotFound[1], s2); done(); } }); }); }); // ========================================================================== // CSS file loading tests // ========================================================================== describe('CSS file loading tests', function() { before(function() { // add test div to body for css tests testEl = document.createElement('div'); testEl.className = 'test-div mui-container'; testEl.style.display = 'inline-block'; document.body.appendChild(testEl); }); afterEach(function() { var els = document.getElementsByTagName('link'), i = els.length, el; // iteratete through stylesheets while (i--) { el = els[i]; // remove test stylesheets if (el.href.indexOf('mocha.css') === -1) { el.parentNode.removeChild(el); } } }); it('should load one file', function(done) { loadjs(['assets/file1.css'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('should load multiple files', function(done) { loadjs(['assets/file1.css', 'assets/file2.css'], { success: function() { assert.equal(testEl.offsetWidth, 200); done(); } }); }); it('should call error callback on one invalid path', function(done) { loadjs(['assets/file1.css', 'assets/file-doesntexist.css'], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { assert.equal(testEl.offsetWidth, 100); assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.css'); done(); } }); }); it('should support mix of css and js', function(done) { loadjs(['assets/file1.css', 'assets/file1.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('should support forced "css!" files', function(done) { loadjs(['css!assets/file1.css'], { success: function() { // loop through files var els = document.getElementsByTagName('link'), i = els.length, el; while (i--) { if (els[i].href.indexOf('file1.css') !== -1) done(); } } }); }); it('supports urls with query arguments', function(done) { loadjs(['assets/file1.css?x=x'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('supports urls with anchor tags', function(done) { loadjs(['assets/file1.css#anchortag'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('supports urls with query arguments and anchor tags', function(done) { loadjs(['assets/file1.css?x=x#anchortag'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('should load external css files', function(done) { this.timeout(0); loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui.min.css'], { success: function() { var styleObj = getComputedStyle(testEl); assert.equal(styleObj.getPropertyValue('padding-left'), '15px'); done(); } }); }); it('should call error on missing external file', function(done) { this.timeout(0); loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui-doesnotexist.min.css'], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { var styleObj = getComputedStyle(testEl); assert.equal(styleObj.getPropertyValue('padding-left'), '0px'); assert.equal(pathsNotFound.length, 1); done(); } }); }); // teardown return after(function() { // remove test div testEl.parentNode.removeChild(testEl); }); }); // ========================================================================== // Image file loading tests // ========================================================================== describe('Image file loading tests', function() { function assertLoaded(src) { // loop through images var imgs = document.getElementsByTagName('img'); Array.prototype.slice.call(imgs).forEach(function(img) { // verify image was loaded if (img.src === src) assert.equal(img.naturalWidth > 0, true); }); } function assertNotLoaded(src) { // loop through images var imgs = document.getElementsByTagName('img'); Array.prototype.slice.call(imgs).forEach(function(img) { // fail if image was loaded if (img.src === src) assert.equal(img.naturalWidth, 0); }); } it('should load one file', function(done) { loadjs(['assets/flash.png'], { success: function() { assertLoaded('assets/flash.png'); done(); } }); }); it('should load multiple files', function(done) { loadjs(['assets/flash.png', 'assets/flash.jpg'], { success: function() { assertLoaded('assets/flash.png'); assertLoaded('assets/flash.jpg'); done(); } }); }); it('detects png|gif|jpg|svg|webp extensions', function(done) { let files = [ 'assets/flash.png', 'assets/flash.gif', 'assets/flash.jpg', 'assets/flash.svg', 'assets/flash.webp' ]; loadjs(files, function() { files.forEach(file => {assertLoaded(file);}); done(); }); }); it('supports urls with query arguments', function(done) { var src = 'assets/flash.png?' + Math.random(); loadjs([src], { success: function() { assertLoaded(src); done(); } }); }); it('supports urls with anchor tags', function(done) { var src = 'assets/flash.png#' + Math.random(); loadjs([src], { success: function() { assertLoaded(src); done(); } }); }); it('supports urls with query arguments and anchor tags', function(done) { var src = 'assets/flash.png'; src += '?' + Math.random(); src += '#' + Math.random(); loadjs([src], { success: function() { assertLoaded(src); done(); } }); }); it('should support forced "img!" files', function(done) { var src = 'assets/flash.png?' + Math.random(); loadjs(['img!' + src], { success: function() { assertLoaded(src); done(); } }); }); it('should call error callback on one invalid path', function(done) { var src1 = 'assets/flash.png?' + Math.random(), src2 = 'assets/flash-doesntexist.png?' + Math.random(); loadjs(['img!' + src1, 'img!' + src2], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assertLoaded(src1); assertNotLoaded(src2); done(); } }); }); it('should support mix of img and js', function(done) { var src = 'assets/flash.png?' + Math.random(); loadjs(['img!' + src, 'assets/file1.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assertLoaded(src); done(); } }); }); it('should load external img files', function(done) { this.timeout(0); var src = 'https://www.muicss.com/static/images/mui-logo.png?'; src += Math.random(); loadjs(['img!' + src], { success: function() { assertLoaded(src); done(); } }); }); it('should call error on missing external file', function(done) { this.timeout(0); var src = 'https://www.muicss.com/static/images/'; src += 'mui-logo-doesntexist.png?' + Math.random(); loadjs(['img!' + src], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { assertNotLoaded(src); done(); } }); }); }); // ========================================================================== // API tests // ========================================================================== describe('API tests', function() { it('should throw an error if bundle is already defined', function() { // define bundle loadjs(['assets/file1.js'], 'bundle'); // define bundle again var fn = function() { loadjs(['assets/file1.js'], 'bundle'); }; expect(fn).to.throw("LoadJS"); }); it('should create a bundle id and a callback inline', function(done) { loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle', { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }); it('should chain loadjs object', function(done) { function bothDone() { if (pathsLoaded['file1.js'] && pathsLoaded['file2.js']) done(); } // define bundles loadjs('assets/file1.js', 'bundle1'); loadjs('assets/file2.js', 'bundle2'); loadjs .ready('bundle1', { success: function() { assert.equal(pathsLoaded['file1.js'], true); bothDone(); }}) .ready('bundle2', { success: function() { assert.equal(pathsLoaded['file2.js'], true); bothDone(); } }); }); it('should handle multiple dependencies', function(done) { loadjs('assets/file1.js', 'bundle1'); loadjs('assets/file2.js', 'bundle2'); loadjs.ready(['bundle1', 'bundle2'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }); it('should error on missing depdendencies', function(done) { loadjs('assets/file1.js', 'bundle1'); loadjs('assets/file-doesntexist.js', 'bundle2'); loadjs.ready(['bundle1', 'bundle2'], { success: function() { throw "Executed success callback"; }, error: function(depsNotFound) { assert.equal(pathsLoaded['file1.js'], true); assert.equal(depsNotFound.length, 1); assert.equal(depsNotFound[0], 'bundle2'); done(); } }); }); it('should execute callbacks on .done()', function(done) { // add handler loadjs.ready('plugin', { success: function() { done(); } }); // execute done loadjs.done('plugin'); }); it('should execute callbacks created after .done()', function(done) { // execute done loadjs.done('plugin'); // add handler loadjs.ready('plugin', { success: function() { done(); } }); }); it('should define bundles', function(done) { // define bundle loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle'); // use 1 second delay to let files load setTimeout(function() { loadjs.ready('bundle', { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }, 1000); }); it('should allow bundle callbacks before definitions', function(done) { // define callback loadjs.ready('bundle', { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); // use 1 second delay setTimeout(function() { loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle'); }, 1000); }); it('should reset dependencies statuses', function() { loadjs(['assets/file1.js'], 'cleared'); loadjs.reset(); // define bundle again var fn = function() { loadjs(['assets/file1.js'], 'cleared'); }; expect(fn).not.to.throw("LoadJS"); }); it('should indicate if bundle has already been defined', function() { loadjs(['assets/file1/js'], 'bundle1'); assert.equal(loadjs.isDefined('bundle1'), true); assert.equal(loadjs.isDefined('bundleXX'), false); }); it('should accept success callback functions to loadjs()', function(done) { loadjs('assets/file1.js', function() { done(); }); }); it('should accept success callback functions to .ready()', function(done) { loadjs.done('plugin'); loadjs.ready('plugin', function() { done(); }); }); it('should return Promise object if returnPromise is true', function() { var prom = loadjs(['assets/file1.js'], {returnPromise: true}); // verify that response object is a Promise assert.equal(prom instanceof Promise, true); }); it('Promise object should support resolutions', function(done) { var prom = loadjs(['assets/file1.js'], {returnPromise: true}); prom.then(function() { assert.equal(pathsLoaded['file1.js'], true); done(); }); }); it('Promise object should support rejections', function(done) { var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true}); prom.then( function(){}, function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); } ); }); it('Promise object should support catches', function(done) { var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true}); prom .catch(function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); }); }); it('supports Promises and success callbacks', function(done) { var numCompleted = 0; function completedFn() { numCompleted += 1; if (numCompleted === 2) done(); }; var prom = loadjs('assets/file1.js', { success: completedFn, returnPromise: true }); prom.then(completedFn); }); it('supports Promises and bundle ready events', function(done) { var numCompleted = 0; function completedFn() { numCompleted += 1; if (numCompleted === 2) done(); }; loadjs('assets/file1.js', 'bundle1', {returnPromise: true}) .then(completedFn); loadjs.ready('bundle1', completedFn); }); }); }); <MSG> most tests passing <DFF> @@ -8,7 +8,7 @@ var pathsLoaded = null, // file register expect = chai.expect; -describe('hello', function() { +describe('loadjs tests', function() { beforeEach(function() { @@ -24,7 +24,19 @@ describe('hello', function() { }); }); - + + it('should call fail callback on invalid path', function(done) { + loadjs(['assets/file-doesntexist.js'], + function() { + throw "Executed success callback"; + }, + function(pathsNotFound) { + // TODO: implement and test pathsNotFound + done(); + }); + }); + + it('should call success callback on two valid paths', function(done) { loadjs(['assets/file1.js', 'assets/file2.js'], function() { assert.equal(pathsLoaded['file1.js'], true); @@ -62,8 +74,10 @@ describe('hello', function() { it('should throw an error if bundle is already defined', function() { + // define bundle loadjs(['assets/file1.js'], 'bundle3'); + // define bundle again var fn = function() { loadjs(['assets/file1.js'], 'bundle3'); }; @@ -72,9 +86,83 @@ describe('hello', function() { }); - it('should call fail callback on invalid path', function(done) { - loadjs(['assets/file-doesntexist.js'], - function() {throw "Executed success callback";}, - function() {done();}); + it('should create an id and a callback inline', function(done) { + loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle4', function() { + assert.equal(pathsLoaded['file1.js'], true); + assert.equal(pathsLoaded['file2.js'], true); + done(); + }); + }); + + + it('should chain loadjs object', function(done) { + function bothDone() { + if (pathsLoaded['file1.js'] && pathsLoaded['file2.js']) done(); + } + + // define bundles + loadjs('assets/file1.js', 'bundle5'); + loadjs('assets/file2.js', 'bundle6'); + + loadjs + .ready('bundle5', function() { + assert.equal(pathsLoaded['file1.js'], true); + bothDone(); + }) + .ready('bundle6', function() { + assert.equal(pathsLoaded['file2.js'], true); + bothDone(); + }); + }); + + + it('should handle multiple dependencies', function(done) { + loadjs('assets/file1.js', 'bundle7'); + loadjs('assets/file2.js', 'bundle8'); + + loadjs.ready(['bundle7', 'bundle8'], function() { + assert.equal(pathsLoaded['file1.js'], true); + assert.equal(pathsLoaded['file2.js'], true); + done(); + }); + }); + + + it('should fail on missing depdendencies', function(done) { + loadjs('assets/file1.js', 'bundle9'); + loadjs('assets/file-doesntexist.js', 'bundle10'); + + loadjs.ready(['bundle9', 'bundle10'], + function() { + throw "Executed success callback"; + }, + function(depsNotFound) { + assert.equal(pathsLoaded['file1.js'], true); + assert.equal(depsNotFound.length, 1); + assert.equal(depsNotFound[0], 'bundle10'); + done(); + }); + }); + + + it('should execute callbacks on .done()', function(done) { + // add handler + loadjs.ready('plugin1', function() { + done(); + }); + + // execute done + loadjs.done('plugin1'); + }); + + + it('should execute callbacks created after .done()', function(done) { + // execute done + loadjs.done('plugin2'); + + // add handler + loadjs.ready('plugin2', function() { + done(); + }); }); });
94
most tests passing
6
.js
js
mit
muicss/loadjs