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
10062650
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update TextMateSharpVersion to 1.0.34 It includes: - Fixes Operations that change non-concurrent collections must have exclusive access: https://github.com/danipen/TextMateSharp/pull/16 - Use .net 6.0 for build the nugets: https://github.com/danipen/TextMateSharp/pull/17 <DFF> @@ -3,7 +3,7 @@ <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> - <TextMateSharpVersion>1.0.31</TextMateSharpVersion> + <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup>
1
Update TextMateSharpVersion to 1.0.34
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062651
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update TextMateSharpVersion to 1.0.34 It includes: - Fixes Operations that change non-concurrent collections must have exclusive access: https://github.com/danipen/TextMateSharp/pull/16 - Use .net 6.0 for build the nugets: https://github.com/danipen/TextMateSharp/pull/17 <DFF> @@ -3,7 +3,7 @@ <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> - <TextMateSharpVersion>1.0.31</TextMateSharpVersion> + <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup>
1
Update TextMateSharpVersion to 1.0.34
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062652
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update TextMateSharpVersion to 1.0.34 It includes: - Fixes Operations that change non-concurrent collections must have exclusive access: https://github.com/danipen/TextMateSharp/pull/16 - Use .net 6.0 for build the nugets: https://github.com/danipen/TextMateSharp/pull/17 <DFF> @@ -3,7 +3,7 @@ <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> - <TextMateSharpVersion>1.0.31</TextMateSharpVersion> + <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup>
1
Update TextMateSharpVersion to 1.0.34
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062653
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update TextMateSharpVersion to 1.0.34 It includes: - Fixes Operations that change non-concurrent collections must have exclusive access: https://github.com/danipen/TextMateSharp/pull/16 - Use .net 6.0 for build the nugets: https://github.com/danipen/TextMateSharp/pull/17 <DFF> @@ -3,7 +3,7 @@ <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> - <TextMateSharpVersion>1.0.31</TextMateSharpVersion> + <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup>
1
Update TextMateSharpVersion to 1.0.34
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062654
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update TextMateSharpVersion to 1.0.34 It includes: - Fixes Operations that change non-concurrent collections must have exclusive access: https://github.com/danipen/TextMateSharp/pull/16 - Use .net 6.0 for build the nugets: https://github.com/danipen/TextMateSharp/pull/17 <DFF> @@ -3,7 +3,7 @@ <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> - <TextMateSharpVersion>1.0.31</TextMateSharpVersion> + <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup>
1
Update TextMateSharpVersion to 1.0.34
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062655
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update TextMateSharpVersion to 1.0.34 It includes: - Fixes Operations that change non-concurrent collections must have exclusive access: https://github.com/danipen/TextMateSharp/pull/16 - Use .net 6.0 for build the nugets: https://github.com/danipen/TextMateSharp/pull/17 <DFF> @@ -3,7 +3,7 @@ <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> - <TextMateSharpVersion>1.0.31</TextMateSharpVersion> + <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup>
1
Update TextMateSharpVersion to 1.0.34
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062656
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update TextMateSharpVersion to 1.0.34 It includes: - Fixes Operations that change non-concurrent collections must have exclusive access: https://github.com/danipen/TextMateSharp/pull/16 - Use .net 6.0 for build the nugets: https://github.com/danipen/TextMateSharp/pull/17 <DFF> @@ -3,7 +3,7 @@ <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> - <TextMateSharpVersion>1.0.31</TextMateSharpVersion> + <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup>
1
Update TextMateSharpVersion to 1.0.34
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062657
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update TextMateSharpVersion to 1.0.34 It includes: - Fixes Operations that change non-concurrent collections must have exclusive access: https://github.com/danipen/TextMateSharp/pull/16 - Use .net 6.0 for build the nugets: https://github.com/danipen/TextMateSharp/pull/17 <DFF> @@ -3,7 +3,7 @@ <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> - <TextMateSharpVersion>1.0.31</TextMateSharpVersion> + <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup>
1
Update TextMateSharpVersion to 1.0.34
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062658
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update TextMateSharpVersion to 1.0.34 It includes: - Fixes Operations that change non-concurrent collections must have exclusive access: https://github.com/danipen/TextMateSharp/pull/16 - Use .net 6.0 for build the nugets: https://github.com/danipen/TextMateSharp/pull/17 <DFF> @@ -3,7 +3,7 @@ <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> - <TextMateSharpVersion>1.0.31</TextMateSharpVersion> + <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup>
1
Update TextMateSharpVersion to 1.0.34
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062659
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update TextMateSharpVersion to 1.0.34 It includes: - Fixes Operations that change non-concurrent collections must have exclusive access: https://github.com/danipen/TextMateSharp/pull/16 - Use .net 6.0 for build the nugets: https://github.com/danipen/TextMateSharp/pull/17 <DFF> @@ -3,7 +3,7 @@ <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> - <TextMateSharpVersion>1.0.31</TextMateSharpVersion> + <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup>
1
Update TextMateSharpVersion to 1.0.34
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062660
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update TextMateSharpVersion to 1.0.34 It includes: - Fixes Operations that change non-concurrent collections must have exclusive access: https://github.com/danipen/TextMateSharp/pull/16 - Use .net 6.0 for build the nugets: https://github.com/danipen/TextMateSharp/pull/17 <DFF> @@ -3,7 +3,7 @@ <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> - <TextMateSharpVersion>1.0.31</TextMateSharpVersion> + <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup>
1
Update TextMateSharpVersion to 1.0.34
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062661
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update TextMateSharpVersion to 1.0.34 It includes: - Fixes Operations that change non-concurrent collections must have exclusive access: https://github.com/danipen/TextMateSharp/pull/16 - Use .net 6.0 for build the nugets: https://github.com/danipen/TextMateSharp/pull/17 <DFF> @@ -3,7 +3,7 @@ <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> - <TextMateSharpVersion>1.0.31</TextMateSharpVersion> + <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup>
1
Update TextMateSharpVersion to 1.0.34
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062662
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update TextMateSharpVersion to 1.0.34 It includes: - Fixes Operations that change non-concurrent collections must have exclusive access: https://github.com/danipen/TextMateSharp/pull/16 - Use .net 6.0 for build the nugets: https://github.com/danipen/TextMateSharp/pull/17 <DFF> @@ -3,7 +3,7 @@ <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> - <TextMateSharpVersion>1.0.31</TextMateSharpVersion> + <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup>
1
Update TextMateSharpVersion to 1.0.34
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062663
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.31</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Update TextMateSharpVersion to 1.0.34 It includes: - Fixes Operations that change non-concurrent collections must have exclusive access: https://github.com/danipen/TextMateSharp/pull/16 - Use .net 6.0 for build the nugets: https://github.com/danipen/TextMateSharp/pull/17 <DFF> @@ -3,7 +3,7 @@ <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> - <TextMateSharpVersion>1.0.31</TextMateSharpVersion> + <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup>
1
Update TextMateSharpVersion to 1.0.34
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062664
<NME> ExtensionMethods.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Xml; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Input; using Avalonia.Media; using Avalonia.VisualTree; namespace AvaloniaEdit.Utils { public static class ExtensionMethods { #region Epsilon / IsClose / CoerceValue /// <summary> /// Epsilon used for <c>IsClose()</c> implementations. /// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin), /// and there's no need to be too accurate (we're dealing with pixels here), /// so we will use the value 0.01. /// Previosly we used 1e-8 but that was causing issues: /// https://community.sharpdevelop.net/forums/t/16048.aspx /// </summary> public const double Epsilon = 0.01; /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this double d1, double d2) { // ReSharper disable once CompareOfFloatsByEqualityOperator if (d1 == d2) // required for infinities return true; return Math.Abs(d1 - d2) < Epsilon; } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Size d1, Size d2) { return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height); } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Vector d1, Vector d2) { return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static double CoerceValue(this double value, double minimum, double maximum) { return Math.Max(Math.Min(value, maximum), minimum); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static int CoerceValue(this int value, int minimum, int maximum) { return Math.Max(Math.Min(value, maximum), minimum); } #endregion #region CreateTypeface /// <summary> /// Creates typeface from the framework element. /// </summary> public static Typeface CreateTypeface(this Control fe) { return new Typeface(fe.GetValue(TextElement.FontFamilyProperty), fe.GetValue(TextElement.FontStyleProperty), fe.GetValue(TextElement.FontWeightProperty), fe.GetValue(TextElement.FontStretchProperty)); } #endregion #region AddRange / Sequence public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements) { foreach (T e in elements) collection.Add(e); } /// <summary> /// Creates an IEnumerable with a single value. /// </summary> public static IEnumerable<T> Sequence<T>(T value) { yield return value; } #endregion #region XML reading ///// <summary> ///// Gets the value of the attribute, or null if the attribute does not exist. ///// </summary> //public static string GetAttributeOrNull(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? attr.Value : null; //} ///// <summary> ///// Gets the value of the attribute as boolean, or null if the attribute does not exist. ///// </summary> //public static bool? GetBoolAttribute(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null; //} /// <summary> /// Gets the value of the attribute as boolean, or null if the attribute does not exist. /// </summary> public static bool? GetBoolAttribute(this XmlReader reader, string attributeName) { string attributeValue = reader.GetAttribute(attributeName); if (attributeValue == null) return null; else return XmlConvert.ToBoolean(attributeValue); } #endregion #region DPI independence //public static Rect TransformToDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return Rect.Transform(rect, matrix); //} //public static Rect TransformFromDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return Rect.Transform(rect, matrix); //} //public static Size TransformToDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return new Size(size.Width * matrix.M11, size.Height * matrix.M22); //} //public static Size TransformFromDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) //} //public static Point TransformFromDevice(this Point point, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return new Point(point.X * matrix.M11, point.Y * matrix.M22); //} #endregion #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) { return new Point(p.X, p.Y); } public static Size ToAvalonia(this System.Drawing.Size s) { return new Size(s.Width, s.Height); } public static Rect ToAvalonia(this System.Drawing.Rectangle rect) { return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia()); } #endregion #region Snap to device pixels public static Point SnapToDevicePixels(this Point p, IVisual targetVisual) { var root = targetVisual.GetVisualRoot(); // Get the root control and its scaling var scaling = new Vector(root.RenderScaling, root.RenderScaling); // Create a matrix to translate from control coordinates to device coordinates. var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling); if (m == null) return p; // Translate the point to device coordinates. var devicePoint = p.Transform(m.Value); // Snap the coordinate to the midpoint between device pixels. devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5); // Translate the point back to control coordinates. var inv = m.Value.Invert(); Point result = devicePoint.Transform(inv); return result; } #endregion public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj) { while (obj != null) { yield return obj; if (obj is Visual v) { obj = (AvaloniaObject)v.GetVisualParent(); } else { break; } } } public static IEnumerable<char> AsEnumerable(this string s) { // ReSharper disable once ForCanBeConvertedToForeach for (var i = 0; i < s.Length; i++) { yield return s[i]; } } [Conditional("DEBUG")] public static void CheckIsFrozen(object o) { if (o is IFreezable f && !f.IsFrozen) Debug.WriteLine("Performance warning: Not frozen: " + f); } [Conditional("DEBUG")] public static void Log(bool condition, string format, params object[] args) { if (condition) { string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace; //Console.WriteLine(output); Debug.WriteLine(output); } } public static bool CapturePointer(this IInputElement element, IPointer device) { device.Capture(element); return device.Captured == element; } public static void ReleasePointerCapture(this IInputElement element, IPointer device) { if (element == device.Captured) { device.Capture(null); } } public static T PeekOrDefault<T>(this ImmutableStack<T> stack) { return stack.IsEmpty ? default(T) : stack.Peek(); } } } <MSG> remove whitespace. <DFF> @@ -178,8 +178,7 @@ namespace AvaloniaEdit.Utils #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { - return new System.Drawing.Point((int)p.X, (int)p.Y); - + return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p)
1
remove whitespace.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062665
<NME> ExtensionMethods.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Xml; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Input; using Avalonia.Media; using Avalonia.VisualTree; namespace AvaloniaEdit.Utils { public static class ExtensionMethods { #region Epsilon / IsClose / CoerceValue /// <summary> /// Epsilon used for <c>IsClose()</c> implementations. /// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin), /// and there's no need to be too accurate (we're dealing with pixels here), /// so we will use the value 0.01. /// Previosly we used 1e-8 but that was causing issues: /// https://community.sharpdevelop.net/forums/t/16048.aspx /// </summary> public const double Epsilon = 0.01; /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this double d1, double d2) { // ReSharper disable once CompareOfFloatsByEqualityOperator if (d1 == d2) // required for infinities return true; return Math.Abs(d1 - d2) < Epsilon; } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Size d1, Size d2) { return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height); } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Vector d1, Vector d2) { return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static double CoerceValue(this double value, double minimum, double maximum) { return Math.Max(Math.Min(value, maximum), minimum); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static int CoerceValue(this int value, int minimum, int maximum) { return Math.Max(Math.Min(value, maximum), minimum); } #endregion #region CreateTypeface /// <summary> /// Creates typeface from the framework element. /// </summary> public static Typeface CreateTypeface(this Control fe) { return new Typeface(fe.GetValue(TextElement.FontFamilyProperty), fe.GetValue(TextElement.FontStyleProperty), fe.GetValue(TextElement.FontWeightProperty), fe.GetValue(TextElement.FontStretchProperty)); } #endregion #region AddRange / Sequence public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements) { foreach (T e in elements) collection.Add(e); } /// <summary> /// Creates an IEnumerable with a single value. /// </summary> public static IEnumerable<T> Sequence<T>(T value) { yield return value; } #endregion #region XML reading ///// <summary> ///// Gets the value of the attribute, or null if the attribute does not exist. ///// </summary> //public static string GetAttributeOrNull(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? attr.Value : null; //} ///// <summary> ///// Gets the value of the attribute as boolean, or null if the attribute does not exist. ///// </summary> //public static bool? GetBoolAttribute(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null; //} /// <summary> /// Gets the value of the attribute as boolean, or null if the attribute does not exist. /// </summary> public static bool? GetBoolAttribute(this XmlReader reader, string attributeName) { string attributeValue = reader.GetAttribute(attributeName); if (attributeValue == null) return null; else return XmlConvert.ToBoolean(attributeValue); } #endregion #region DPI independence //public static Rect TransformToDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return Rect.Transform(rect, matrix); //} //public static Rect TransformFromDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return Rect.Transform(rect, matrix); //} //public static Size TransformToDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return new Size(size.Width * matrix.M11, size.Height * matrix.M22); //} //public static Size TransformFromDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) //} //public static Point TransformFromDevice(this Point point, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return new Point(point.X * matrix.M11, point.Y * matrix.M22); //} #endregion #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) { return new Point(p.X, p.Y); } public static Size ToAvalonia(this System.Drawing.Size s) { return new Size(s.Width, s.Height); } public static Rect ToAvalonia(this System.Drawing.Rectangle rect) { return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia()); } #endregion #region Snap to device pixels public static Point SnapToDevicePixels(this Point p, IVisual targetVisual) { var root = targetVisual.GetVisualRoot(); // Get the root control and its scaling var scaling = new Vector(root.RenderScaling, root.RenderScaling); // Create a matrix to translate from control coordinates to device coordinates. var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling); if (m == null) return p; // Translate the point to device coordinates. var devicePoint = p.Transform(m.Value); // Snap the coordinate to the midpoint between device pixels. devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5); // Translate the point back to control coordinates. var inv = m.Value.Invert(); Point result = devicePoint.Transform(inv); return result; } #endregion public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj) { while (obj != null) { yield return obj; if (obj is Visual v) { obj = (AvaloniaObject)v.GetVisualParent(); } else { break; } } } public static IEnumerable<char> AsEnumerable(this string s) { // ReSharper disable once ForCanBeConvertedToForeach for (var i = 0; i < s.Length; i++) { yield return s[i]; } } [Conditional("DEBUG")] public static void CheckIsFrozen(object o) { if (o is IFreezable f && !f.IsFrozen) Debug.WriteLine("Performance warning: Not frozen: " + f); } [Conditional("DEBUG")] public static void Log(bool condition, string format, params object[] args) { if (condition) { string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace; //Console.WriteLine(output); Debug.WriteLine(output); } } public static bool CapturePointer(this IInputElement element, IPointer device) { device.Capture(element); return device.Captured == element; } public static void ReleasePointerCapture(this IInputElement element, IPointer device) { if (element == device.Captured) { device.Capture(null); } } public static T PeekOrDefault<T>(this ImmutableStack<T> stack) { return stack.IsEmpty ? default(T) : stack.Peek(); } } } <MSG> remove whitespace. <DFF> @@ -178,8 +178,7 @@ namespace AvaloniaEdit.Utils #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { - return new System.Drawing.Point((int)p.X, (int)p.Y); - + return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p)
1
remove whitespace.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062666
<NME> ExtensionMethods.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Xml; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Input; using Avalonia.Media; using Avalonia.VisualTree; namespace AvaloniaEdit.Utils { public static class ExtensionMethods { #region Epsilon / IsClose / CoerceValue /// <summary> /// Epsilon used for <c>IsClose()</c> implementations. /// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin), /// and there's no need to be too accurate (we're dealing with pixels here), /// so we will use the value 0.01. /// Previosly we used 1e-8 but that was causing issues: /// https://community.sharpdevelop.net/forums/t/16048.aspx /// </summary> public const double Epsilon = 0.01; /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this double d1, double d2) { // ReSharper disable once CompareOfFloatsByEqualityOperator if (d1 == d2) // required for infinities return true; return Math.Abs(d1 - d2) < Epsilon; } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Size d1, Size d2) { return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height); } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Vector d1, Vector d2) { return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static double CoerceValue(this double value, double minimum, double maximum) { return Math.Max(Math.Min(value, maximum), minimum); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static int CoerceValue(this int value, int minimum, int maximum) { return Math.Max(Math.Min(value, maximum), minimum); } #endregion #region CreateTypeface /// <summary> /// Creates typeface from the framework element. /// </summary> public static Typeface CreateTypeface(this Control fe) { return new Typeface(fe.GetValue(TextElement.FontFamilyProperty), fe.GetValue(TextElement.FontStyleProperty), fe.GetValue(TextElement.FontWeightProperty), fe.GetValue(TextElement.FontStretchProperty)); } #endregion #region AddRange / Sequence public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements) { foreach (T e in elements) collection.Add(e); } /// <summary> /// Creates an IEnumerable with a single value. /// </summary> public static IEnumerable<T> Sequence<T>(T value) { yield return value; } #endregion #region XML reading ///// <summary> ///// Gets the value of the attribute, or null if the attribute does not exist. ///// </summary> //public static string GetAttributeOrNull(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? attr.Value : null; //} ///// <summary> ///// Gets the value of the attribute as boolean, or null if the attribute does not exist. ///// </summary> //public static bool? GetBoolAttribute(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null; //} /// <summary> /// Gets the value of the attribute as boolean, or null if the attribute does not exist. /// </summary> public static bool? GetBoolAttribute(this XmlReader reader, string attributeName) { string attributeValue = reader.GetAttribute(attributeName); if (attributeValue == null) return null; else return XmlConvert.ToBoolean(attributeValue); } #endregion #region DPI independence //public static Rect TransformToDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return Rect.Transform(rect, matrix); //} //public static Rect TransformFromDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return Rect.Transform(rect, matrix); //} //public static Size TransformToDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return new Size(size.Width * matrix.M11, size.Height * matrix.M22); //} //public static Size TransformFromDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) //} //public static Point TransformFromDevice(this Point point, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return new Point(point.X * matrix.M11, point.Y * matrix.M22); //} #endregion #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) { return new Point(p.X, p.Y); } public static Size ToAvalonia(this System.Drawing.Size s) { return new Size(s.Width, s.Height); } public static Rect ToAvalonia(this System.Drawing.Rectangle rect) { return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia()); } #endregion #region Snap to device pixels public static Point SnapToDevicePixels(this Point p, IVisual targetVisual) { var root = targetVisual.GetVisualRoot(); // Get the root control and its scaling var scaling = new Vector(root.RenderScaling, root.RenderScaling); // Create a matrix to translate from control coordinates to device coordinates. var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling); if (m == null) return p; // Translate the point to device coordinates. var devicePoint = p.Transform(m.Value); // Snap the coordinate to the midpoint between device pixels. devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5); // Translate the point back to control coordinates. var inv = m.Value.Invert(); Point result = devicePoint.Transform(inv); return result; } #endregion public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj) { while (obj != null) { yield return obj; if (obj is Visual v) { obj = (AvaloniaObject)v.GetVisualParent(); } else { break; } } } public static IEnumerable<char> AsEnumerable(this string s) { // ReSharper disable once ForCanBeConvertedToForeach for (var i = 0; i < s.Length; i++) { yield return s[i]; } } [Conditional("DEBUG")] public static void CheckIsFrozen(object o) { if (o is IFreezable f && !f.IsFrozen) Debug.WriteLine("Performance warning: Not frozen: " + f); } [Conditional("DEBUG")] public static void Log(bool condition, string format, params object[] args) { if (condition) { string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace; //Console.WriteLine(output); Debug.WriteLine(output); } } public static bool CapturePointer(this IInputElement element, IPointer device) { device.Capture(element); return device.Captured == element; } public static void ReleasePointerCapture(this IInputElement element, IPointer device) { if (element == device.Captured) { device.Capture(null); } } public static T PeekOrDefault<T>(this ImmutableStack<T> stack) { return stack.IsEmpty ? default(T) : stack.Peek(); } } } <MSG> remove whitespace. <DFF> @@ -178,8 +178,7 @@ namespace AvaloniaEdit.Utils #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { - return new System.Drawing.Point((int)p.X, (int)p.Y); - + return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p)
1
remove whitespace.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062667
<NME> ExtensionMethods.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Xml; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Input; using Avalonia.Media; using Avalonia.VisualTree; namespace AvaloniaEdit.Utils { public static class ExtensionMethods { #region Epsilon / IsClose / CoerceValue /// <summary> /// Epsilon used for <c>IsClose()</c> implementations. /// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin), /// and there's no need to be too accurate (we're dealing with pixels here), /// so we will use the value 0.01. /// Previosly we used 1e-8 but that was causing issues: /// https://community.sharpdevelop.net/forums/t/16048.aspx /// </summary> public const double Epsilon = 0.01; /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this double d1, double d2) { // ReSharper disable once CompareOfFloatsByEqualityOperator if (d1 == d2) // required for infinities return true; return Math.Abs(d1 - d2) < Epsilon; } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Size d1, Size d2) { return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height); } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Vector d1, Vector d2) { return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static double CoerceValue(this double value, double minimum, double maximum) { return Math.Max(Math.Min(value, maximum), minimum); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static int CoerceValue(this int value, int minimum, int maximum) { return Math.Max(Math.Min(value, maximum), minimum); } #endregion #region CreateTypeface /// <summary> /// Creates typeface from the framework element. /// </summary> public static Typeface CreateTypeface(this Control fe) { return new Typeface(fe.GetValue(TextElement.FontFamilyProperty), fe.GetValue(TextElement.FontStyleProperty), fe.GetValue(TextElement.FontWeightProperty), fe.GetValue(TextElement.FontStretchProperty)); } #endregion #region AddRange / Sequence public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements) { foreach (T e in elements) collection.Add(e); } /// <summary> /// Creates an IEnumerable with a single value. /// </summary> public static IEnumerable<T> Sequence<T>(T value) { yield return value; } #endregion #region XML reading ///// <summary> ///// Gets the value of the attribute, or null if the attribute does not exist. ///// </summary> //public static string GetAttributeOrNull(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? attr.Value : null; //} ///// <summary> ///// Gets the value of the attribute as boolean, or null if the attribute does not exist. ///// </summary> //public static bool? GetBoolAttribute(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null; //} /// <summary> /// Gets the value of the attribute as boolean, or null if the attribute does not exist. /// </summary> public static bool? GetBoolAttribute(this XmlReader reader, string attributeName) { string attributeValue = reader.GetAttribute(attributeName); if (attributeValue == null) return null; else return XmlConvert.ToBoolean(attributeValue); } #endregion #region DPI independence //public static Rect TransformToDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return Rect.Transform(rect, matrix); //} //public static Rect TransformFromDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return Rect.Transform(rect, matrix); //} //public static Size TransformToDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return new Size(size.Width * matrix.M11, size.Height * matrix.M22); //} //public static Size TransformFromDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) //} //public static Point TransformFromDevice(this Point point, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return new Point(point.X * matrix.M11, point.Y * matrix.M22); //} #endregion #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) { return new Point(p.X, p.Y); } public static Size ToAvalonia(this System.Drawing.Size s) { return new Size(s.Width, s.Height); } public static Rect ToAvalonia(this System.Drawing.Rectangle rect) { return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia()); } #endregion #region Snap to device pixels public static Point SnapToDevicePixels(this Point p, IVisual targetVisual) { var root = targetVisual.GetVisualRoot(); // Get the root control and its scaling var scaling = new Vector(root.RenderScaling, root.RenderScaling); // Create a matrix to translate from control coordinates to device coordinates. var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling); if (m == null) return p; // Translate the point to device coordinates. var devicePoint = p.Transform(m.Value); // Snap the coordinate to the midpoint between device pixels. devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5); // Translate the point back to control coordinates. var inv = m.Value.Invert(); Point result = devicePoint.Transform(inv); return result; } #endregion public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj) { while (obj != null) { yield return obj; if (obj is Visual v) { obj = (AvaloniaObject)v.GetVisualParent(); } else { break; } } } public static IEnumerable<char> AsEnumerable(this string s) { // ReSharper disable once ForCanBeConvertedToForeach for (var i = 0; i < s.Length; i++) { yield return s[i]; } } [Conditional("DEBUG")] public static void CheckIsFrozen(object o) { if (o is IFreezable f && !f.IsFrozen) Debug.WriteLine("Performance warning: Not frozen: " + f); } [Conditional("DEBUG")] public static void Log(bool condition, string format, params object[] args) { if (condition) { string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace; //Console.WriteLine(output); Debug.WriteLine(output); } } public static bool CapturePointer(this IInputElement element, IPointer device) { device.Capture(element); return device.Captured == element; } public static void ReleasePointerCapture(this IInputElement element, IPointer device) { if (element == device.Captured) { device.Capture(null); } } public static T PeekOrDefault<T>(this ImmutableStack<T> stack) { return stack.IsEmpty ? default(T) : stack.Peek(); } } } <MSG> remove whitespace. <DFF> @@ -178,8 +178,7 @@ namespace AvaloniaEdit.Utils #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { - return new System.Drawing.Point((int)p.X, (int)p.Y); - + return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p)
1
remove whitespace.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062668
<NME> ExtensionMethods.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Xml; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Input; using Avalonia.Media; using Avalonia.VisualTree; namespace AvaloniaEdit.Utils { public static class ExtensionMethods { #region Epsilon / IsClose / CoerceValue /// <summary> /// Epsilon used for <c>IsClose()</c> implementations. /// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin), /// and there's no need to be too accurate (we're dealing with pixels here), /// so we will use the value 0.01. /// Previosly we used 1e-8 but that was causing issues: /// https://community.sharpdevelop.net/forums/t/16048.aspx /// </summary> public const double Epsilon = 0.01; /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this double d1, double d2) { // ReSharper disable once CompareOfFloatsByEqualityOperator if (d1 == d2) // required for infinities return true; return Math.Abs(d1 - d2) < Epsilon; } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Size d1, Size d2) { return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height); } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Vector d1, Vector d2) { return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static double CoerceValue(this double value, double minimum, double maximum) { return Math.Max(Math.Min(value, maximum), minimum); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static int CoerceValue(this int value, int minimum, int maximum) { return Math.Max(Math.Min(value, maximum), minimum); } #endregion #region CreateTypeface /// <summary> /// Creates typeface from the framework element. /// </summary> public static Typeface CreateTypeface(this Control fe) { return new Typeface(fe.GetValue(TextElement.FontFamilyProperty), fe.GetValue(TextElement.FontStyleProperty), fe.GetValue(TextElement.FontWeightProperty), fe.GetValue(TextElement.FontStretchProperty)); } #endregion #region AddRange / Sequence public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements) { foreach (T e in elements) collection.Add(e); } /// <summary> /// Creates an IEnumerable with a single value. /// </summary> public static IEnumerable<T> Sequence<T>(T value) { yield return value; } #endregion #region XML reading ///// <summary> ///// Gets the value of the attribute, or null if the attribute does not exist. ///// </summary> //public static string GetAttributeOrNull(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? attr.Value : null; //} ///// <summary> ///// Gets the value of the attribute as boolean, or null if the attribute does not exist. ///// </summary> //public static bool? GetBoolAttribute(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null; //} /// <summary> /// Gets the value of the attribute as boolean, or null if the attribute does not exist. /// </summary> public static bool? GetBoolAttribute(this XmlReader reader, string attributeName) { string attributeValue = reader.GetAttribute(attributeName); if (attributeValue == null) return null; else return XmlConvert.ToBoolean(attributeValue); } #endregion #region DPI independence //public static Rect TransformToDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return Rect.Transform(rect, matrix); //} //public static Rect TransformFromDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return Rect.Transform(rect, matrix); //} //public static Size TransformToDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return new Size(size.Width * matrix.M11, size.Height * matrix.M22); //} //public static Size TransformFromDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) //} //public static Point TransformFromDevice(this Point point, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return new Point(point.X * matrix.M11, point.Y * matrix.M22); //} #endregion #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) { return new Point(p.X, p.Y); } public static Size ToAvalonia(this System.Drawing.Size s) { return new Size(s.Width, s.Height); } public static Rect ToAvalonia(this System.Drawing.Rectangle rect) { return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia()); } #endregion #region Snap to device pixels public static Point SnapToDevicePixels(this Point p, IVisual targetVisual) { var root = targetVisual.GetVisualRoot(); // Get the root control and its scaling var scaling = new Vector(root.RenderScaling, root.RenderScaling); // Create a matrix to translate from control coordinates to device coordinates. var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling); if (m == null) return p; // Translate the point to device coordinates. var devicePoint = p.Transform(m.Value); // Snap the coordinate to the midpoint between device pixels. devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5); // Translate the point back to control coordinates. var inv = m.Value.Invert(); Point result = devicePoint.Transform(inv); return result; } #endregion public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj) { while (obj != null) { yield return obj; if (obj is Visual v) { obj = (AvaloniaObject)v.GetVisualParent(); } else { break; } } } public static IEnumerable<char> AsEnumerable(this string s) { // ReSharper disable once ForCanBeConvertedToForeach for (var i = 0; i < s.Length; i++) { yield return s[i]; } } [Conditional("DEBUG")] public static void CheckIsFrozen(object o) { if (o is IFreezable f && !f.IsFrozen) Debug.WriteLine("Performance warning: Not frozen: " + f); } [Conditional("DEBUG")] public static void Log(bool condition, string format, params object[] args) { if (condition) { string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace; //Console.WriteLine(output); Debug.WriteLine(output); } } public static bool CapturePointer(this IInputElement element, IPointer device) { device.Capture(element); return device.Captured == element; } public static void ReleasePointerCapture(this IInputElement element, IPointer device) { if (element == device.Captured) { device.Capture(null); } } public static T PeekOrDefault<T>(this ImmutableStack<T> stack) { return stack.IsEmpty ? default(T) : stack.Peek(); } } } <MSG> remove whitespace. <DFF> @@ -178,8 +178,7 @@ namespace AvaloniaEdit.Utils #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { - return new System.Drawing.Point((int)p.X, (int)p.Y); - + return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p)
1
remove whitespace.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062669
<NME> ExtensionMethods.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Xml; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Input; using Avalonia.Media; using Avalonia.VisualTree; namespace AvaloniaEdit.Utils { public static class ExtensionMethods { #region Epsilon / IsClose / CoerceValue /// <summary> /// Epsilon used for <c>IsClose()</c> implementations. /// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin), /// and there's no need to be too accurate (we're dealing with pixels here), /// so we will use the value 0.01. /// Previosly we used 1e-8 but that was causing issues: /// https://community.sharpdevelop.net/forums/t/16048.aspx /// </summary> public const double Epsilon = 0.01; /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this double d1, double d2) { // ReSharper disable once CompareOfFloatsByEqualityOperator if (d1 == d2) // required for infinities return true; return Math.Abs(d1 - d2) < Epsilon; } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Size d1, Size d2) { return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height); } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Vector d1, Vector d2) { return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static double CoerceValue(this double value, double minimum, double maximum) { return Math.Max(Math.Min(value, maximum), minimum); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static int CoerceValue(this int value, int minimum, int maximum) { return Math.Max(Math.Min(value, maximum), minimum); } #endregion #region CreateTypeface /// <summary> /// Creates typeface from the framework element. /// </summary> public static Typeface CreateTypeface(this Control fe) { return new Typeface(fe.GetValue(TextElement.FontFamilyProperty), fe.GetValue(TextElement.FontStyleProperty), fe.GetValue(TextElement.FontWeightProperty), fe.GetValue(TextElement.FontStretchProperty)); } #endregion #region AddRange / Sequence public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements) { foreach (T e in elements) collection.Add(e); } /// <summary> /// Creates an IEnumerable with a single value. /// </summary> public static IEnumerable<T> Sequence<T>(T value) { yield return value; } #endregion #region XML reading ///// <summary> ///// Gets the value of the attribute, or null if the attribute does not exist. ///// </summary> //public static string GetAttributeOrNull(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? attr.Value : null; //} ///// <summary> ///// Gets the value of the attribute as boolean, or null if the attribute does not exist. ///// </summary> //public static bool? GetBoolAttribute(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null; //} /// <summary> /// Gets the value of the attribute as boolean, or null if the attribute does not exist. /// </summary> public static bool? GetBoolAttribute(this XmlReader reader, string attributeName) { string attributeValue = reader.GetAttribute(attributeName); if (attributeValue == null) return null; else return XmlConvert.ToBoolean(attributeValue); } #endregion #region DPI independence //public static Rect TransformToDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return Rect.Transform(rect, matrix); //} //public static Rect TransformFromDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return Rect.Transform(rect, matrix); //} //public static Size TransformToDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return new Size(size.Width * matrix.M11, size.Height * matrix.M22); //} //public static Size TransformFromDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) //} //public static Point TransformFromDevice(this Point point, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return new Point(point.X * matrix.M11, point.Y * matrix.M22); //} #endregion #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) { return new Point(p.X, p.Y); } public static Size ToAvalonia(this System.Drawing.Size s) { return new Size(s.Width, s.Height); } public static Rect ToAvalonia(this System.Drawing.Rectangle rect) { return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia()); } #endregion #region Snap to device pixels public static Point SnapToDevicePixels(this Point p, IVisual targetVisual) { var root = targetVisual.GetVisualRoot(); // Get the root control and its scaling var scaling = new Vector(root.RenderScaling, root.RenderScaling); // Create a matrix to translate from control coordinates to device coordinates. var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling); if (m == null) return p; // Translate the point to device coordinates. var devicePoint = p.Transform(m.Value); // Snap the coordinate to the midpoint between device pixels. devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5); // Translate the point back to control coordinates. var inv = m.Value.Invert(); Point result = devicePoint.Transform(inv); return result; } #endregion public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj) { while (obj != null) { yield return obj; if (obj is Visual v) { obj = (AvaloniaObject)v.GetVisualParent(); } else { break; } } } public static IEnumerable<char> AsEnumerable(this string s) { // ReSharper disable once ForCanBeConvertedToForeach for (var i = 0; i < s.Length; i++) { yield return s[i]; } } [Conditional("DEBUG")] public static void CheckIsFrozen(object o) { if (o is IFreezable f && !f.IsFrozen) Debug.WriteLine("Performance warning: Not frozen: " + f); } [Conditional("DEBUG")] public static void Log(bool condition, string format, params object[] args) { if (condition) { string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace; //Console.WriteLine(output); Debug.WriteLine(output); } } public static bool CapturePointer(this IInputElement element, IPointer device) { device.Capture(element); return device.Captured == element; } public static void ReleasePointerCapture(this IInputElement element, IPointer device) { if (element == device.Captured) { device.Capture(null); } } public static T PeekOrDefault<T>(this ImmutableStack<T> stack) { return stack.IsEmpty ? default(T) : stack.Peek(); } } } <MSG> remove whitespace. <DFF> @@ -178,8 +178,7 @@ namespace AvaloniaEdit.Utils #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { - return new System.Drawing.Point((int)p.X, (int)p.Y); - + return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p)
1
remove whitespace.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062670
<NME> ExtensionMethods.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Xml; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Input; using Avalonia.Media; using Avalonia.VisualTree; namespace AvaloniaEdit.Utils { public static class ExtensionMethods { #region Epsilon / IsClose / CoerceValue /// <summary> /// Epsilon used for <c>IsClose()</c> implementations. /// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin), /// and there's no need to be too accurate (we're dealing with pixels here), /// so we will use the value 0.01. /// Previosly we used 1e-8 but that was causing issues: /// https://community.sharpdevelop.net/forums/t/16048.aspx /// </summary> public const double Epsilon = 0.01; /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this double d1, double d2) { // ReSharper disable once CompareOfFloatsByEqualityOperator if (d1 == d2) // required for infinities return true; return Math.Abs(d1 - d2) < Epsilon; } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Size d1, Size d2) { return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height); } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Vector d1, Vector d2) { return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static double CoerceValue(this double value, double minimum, double maximum) { return Math.Max(Math.Min(value, maximum), minimum); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static int CoerceValue(this int value, int minimum, int maximum) { return Math.Max(Math.Min(value, maximum), minimum); } #endregion #region CreateTypeface /// <summary> /// Creates typeface from the framework element. /// </summary> public static Typeface CreateTypeface(this Control fe) { return new Typeface(fe.GetValue(TextElement.FontFamilyProperty), fe.GetValue(TextElement.FontStyleProperty), fe.GetValue(TextElement.FontWeightProperty), fe.GetValue(TextElement.FontStretchProperty)); } #endregion #region AddRange / Sequence public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements) { foreach (T e in elements) collection.Add(e); } /// <summary> /// Creates an IEnumerable with a single value. /// </summary> public static IEnumerable<T> Sequence<T>(T value) { yield return value; } #endregion #region XML reading ///// <summary> ///// Gets the value of the attribute, or null if the attribute does not exist. ///// </summary> //public static string GetAttributeOrNull(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? attr.Value : null; //} ///// <summary> ///// Gets the value of the attribute as boolean, or null if the attribute does not exist. ///// </summary> //public static bool? GetBoolAttribute(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null; //} /// <summary> /// Gets the value of the attribute as boolean, or null if the attribute does not exist. /// </summary> public static bool? GetBoolAttribute(this XmlReader reader, string attributeName) { string attributeValue = reader.GetAttribute(attributeName); if (attributeValue == null) return null; else return XmlConvert.ToBoolean(attributeValue); } #endregion #region DPI independence //public static Rect TransformToDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return Rect.Transform(rect, matrix); //} //public static Rect TransformFromDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return Rect.Transform(rect, matrix); //} //public static Size TransformToDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return new Size(size.Width * matrix.M11, size.Height * matrix.M22); //} //public static Size TransformFromDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) //} //public static Point TransformFromDevice(this Point point, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return new Point(point.X * matrix.M11, point.Y * matrix.M22); //} #endregion #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) { return new Point(p.X, p.Y); } public static Size ToAvalonia(this System.Drawing.Size s) { return new Size(s.Width, s.Height); } public static Rect ToAvalonia(this System.Drawing.Rectangle rect) { return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia()); } #endregion #region Snap to device pixels public static Point SnapToDevicePixels(this Point p, IVisual targetVisual) { var root = targetVisual.GetVisualRoot(); // Get the root control and its scaling var scaling = new Vector(root.RenderScaling, root.RenderScaling); // Create a matrix to translate from control coordinates to device coordinates. var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling); if (m == null) return p; // Translate the point to device coordinates. var devicePoint = p.Transform(m.Value); // Snap the coordinate to the midpoint between device pixels. devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5); // Translate the point back to control coordinates. var inv = m.Value.Invert(); Point result = devicePoint.Transform(inv); return result; } #endregion public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj) { while (obj != null) { yield return obj; if (obj is Visual v) { obj = (AvaloniaObject)v.GetVisualParent(); } else { break; } } } public static IEnumerable<char> AsEnumerable(this string s) { // ReSharper disable once ForCanBeConvertedToForeach for (var i = 0; i < s.Length; i++) { yield return s[i]; } } [Conditional("DEBUG")] public static void CheckIsFrozen(object o) { if (o is IFreezable f && !f.IsFrozen) Debug.WriteLine("Performance warning: Not frozen: " + f); } [Conditional("DEBUG")] public static void Log(bool condition, string format, params object[] args) { if (condition) { string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace; //Console.WriteLine(output); Debug.WriteLine(output); } } public static bool CapturePointer(this IInputElement element, IPointer device) { device.Capture(element); return device.Captured == element; } public static void ReleasePointerCapture(this IInputElement element, IPointer device) { if (element == device.Captured) { device.Capture(null); } } public static T PeekOrDefault<T>(this ImmutableStack<T> stack) { return stack.IsEmpty ? default(T) : stack.Peek(); } } } <MSG> remove whitespace. <DFF> @@ -178,8 +178,7 @@ namespace AvaloniaEdit.Utils #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { - return new System.Drawing.Point((int)p.X, (int)p.Y); - + return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p)
1
remove whitespace.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062671
<NME> ExtensionMethods.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Xml; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Input; using Avalonia.Media; using Avalonia.VisualTree; namespace AvaloniaEdit.Utils { public static class ExtensionMethods { #region Epsilon / IsClose / CoerceValue /// <summary> /// Epsilon used for <c>IsClose()</c> implementations. /// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin), /// and there's no need to be too accurate (we're dealing with pixels here), /// so we will use the value 0.01. /// Previosly we used 1e-8 but that was causing issues: /// https://community.sharpdevelop.net/forums/t/16048.aspx /// </summary> public const double Epsilon = 0.01; /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this double d1, double d2) { // ReSharper disable once CompareOfFloatsByEqualityOperator if (d1 == d2) // required for infinities return true; return Math.Abs(d1 - d2) < Epsilon; } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Size d1, Size d2) { return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height); } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Vector d1, Vector d2) { return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static double CoerceValue(this double value, double minimum, double maximum) { return Math.Max(Math.Min(value, maximum), minimum); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static int CoerceValue(this int value, int minimum, int maximum) { return Math.Max(Math.Min(value, maximum), minimum); } #endregion #region CreateTypeface /// <summary> /// Creates typeface from the framework element. /// </summary> public static Typeface CreateTypeface(this Control fe) { return new Typeface(fe.GetValue(TextElement.FontFamilyProperty), fe.GetValue(TextElement.FontStyleProperty), fe.GetValue(TextElement.FontWeightProperty), fe.GetValue(TextElement.FontStretchProperty)); } #endregion #region AddRange / Sequence public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements) { foreach (T e in elements) collection.Add(e); } /// <summary> /// Creates an IEnumerable with a single value. /// </summary> public static IEnumerable<T> Sequence<T>(T value) { yield return value; } #endregion #region XML reading ///// <summary> ///// Gets the value of the attribute, or null if the attribute does not exist. ///// </summary> //public static string GetAttributeOrNull(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? attr.Value : null; //} ///// <summary> ///// Gets the value of the attribute as boolean, or null if the attribute does not exist. ///// </summary> //public static bool? GetBoolAttribute(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null; //} /// <summary> /// Gets the value of the attribute as boolean, or null if the attribute does not exist. /// </summary> public static bool? GetBoolAttribute(this XmlReader reader, string attributeName) { string attributeValue = reader.GetAttribute(attributeName); if (attributeValue == null) return null; else return XmlConvert.ToBoolean(attributeValue); } #endregion #region DPI independence //public static Rect TransformToDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return Rect.Transform(rect, matrix); //} //public static Rect TransformFromDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return Rect.Transform(rect, matrix); //} //public static Size TransformToDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return new Size(size.Width * matrix.M11, size.Height * matrix.M22); //} //public static Size TransformFromDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) //} //public static Point TransformFromDevice(this Point point, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return new Point(point.X * matrix.M11, point.Y * matrix.M22); //} #endregion #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) { return new Point(p.X, p.Y); } public static Size ToAvalonia(this System.Drawing.Size s) { return new Size(s.Width, s.Height); } public static Rect ToAvalonia(this System.Drawing.Rectangle rect) { return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia()); } #endregion #region Snap to device pixels public static Point SnapToDevicePixels(this Point p, IVisual targetVisual) { var root = targetVisual.GetVisualRoot(); // Get the root control and its scaling var scaling = new Vector(root.RenderScaling, root.RenderScaling); // Create a matrix to translate from control coordinates to device coordinates. var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling); if (m == null) return p; // Translate the point to device coordinates. var devicePoint = p.Transform(m.Value); // Snap the coordinate to the midpoint between device pixels. devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5); // Translate the point back to control coordinates. var inv = m.Value.Invert(); Point result = devicePoint.Transform(inv); return result; } #endregion public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj) { while (obj != null) { yield return obj; if (obj is Visual v) { obj = (AvaloniaObject)v.GetVisualParent(); } else { break; } } } public static IEnumerable<char> AsEnumerable(this string s) { // ReSharper disable once ForCanBeConvertedToForeach for (var i = 0; i < s.Length; i++) { yield return s[i]; } } [Conditional("DEBUG")] public static void CheckIsFrozen(object o) { if (o is IFreezable f && !f.IsFrozen) Debug.WriteLine("Performance warning: Not frozen: " + f); } [Conditional("DEBUG")] public static void Log(bool condition, string format, params object[] args) { if (condition) { string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace; //Console.WriteLine(output); Debug.WriteLine(output); } } public static bool CapturePointer(this IInputElement element, IPointer device) { device.Capture(element); return device.Captured == element; } public static void ReleasePointerCapture(this IInputElement element, IPointer device) { if (element == device.Captured) { device.Capture(null); } } public static T PeekOrDefault<T>(this ImmutableStack<T> stack) { return stack.IsEmpty ? default(T) : stack.Peek(); } } } <MSG> remove whitespace. <DFF> @@ -178,8 +178,7 @@ namespace AvaloniaEdit.Utils #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { - return new System.Drawing.Point((int)p.X, (int)p.Y); - + return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p)
1
remove whitespace.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062672
<NME> ExtensionMethods.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Xml; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Input; using Avalonia.Media; using Avalonia.VisualTree; namespace AvaloniaEdit.Utils { public static class ExtensionMethods { #region Epsilon / IsClose / CoerceValue /// <summary> /// Epsilon used for <c>IsClose()</c> implementations. /// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin), /// and there's no need to be too accurate (we're dealing with pixels here), /// so we will use the value 0.01. /// Previosly we used 1e-8 but that was causing issues: /// https://community.sharpdevelop.net/forums/t/16048.aspx /// </summary> public const double Epsilon = 0.01; /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this double d1, double d2) { // ReSharper disable once CompareOfFloatsByEqualityOperator if (d1 == d2) // required for infinities return true; return Math.Abs(d1 - d2) < Epsilon; } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Size d1, Size d2) { return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height); } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Vector d1, Vector d2) { return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static double CoerceValue(this double value, double minimum, double maximum) { return Math.Max(Math.Min(value, maximum), minimum); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static int CoerceValue(this int value, int minimum, int maximum) { return Math.Max(Math.Min(value, maximum), minimum); } #endregion #region CreateTypeface /// <summary> /// Creates typeface from the framework element. /// </summary> public static Typeface CreateTypeface(this Control fe) { return new Typeface(fe.GetValue(TextElement.FontFamilyProperty), fe.GetValue(TextElement.FontStyleProperty), fe.GetValue(TextElement.FontWeightProperty), fe.GetValue(TextElement.FontStretchProperty)); } #endregion #region AddRange / Sequence public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements) { foreach (T e in elements) collection.Add(e); } /// <summary> /// Creates an IEnumerable with a single value. /// </summary> public static IEnumerable<T> Sequence<T>(T value) { yield return value; } #endregion #region XML reading ///// <summary> ///// Gets the value of the attribute, or null if the attribute does not exist. ///// </summary> //public static string GetAttributeOrNull(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? attr.Value : null; //} ///// <summary> ///// Gets the value of the attribute as boolean, or null if the attribute does not exist. ///// </summary> //public static bool? GetBoolAttribute(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null; //} /// <summary> /// Gets the value of the attribute as boolean, or null if the attribute does not exist. /// </summary> public static bool? GetBoolAttribute(this XmlReader reader, string attributeName) { string attributeValue = reader.GetAttribute(attributeName); if (attributeValue == null) return null; else return XmlConvert.ToBoolean(attributeValue); } #endregion #region DPI independence //public static Rect TransformToDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return Rect.Transform(rect, matrix); //} //public static Rect TransformFromDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return Rect.Transform(rect, matrix); //} //public static Size TransformToDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return new Size(size.Width * matrix.M11, size.Height * matrix.M22); //} //public static Size TransformFromDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) //} //public static Point TransformFromDevice(this Point point, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return new Point(point.X * matrix.M11, point.Y * matrix.M22); //} #endregion #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) { return new Point(p.X, p.Y); } public static Size ToAvalonia(this System.Drawing.Size s) { return new Size(s.Width, s.Height); } public static Rect ToAvalonia(this System.Drawing.Rectangle rect) { return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia()); } #endregion #region Snap to device pixels public static Point SnapToDevicePixels(this Point p, IVisual targetVisual) { var root = targetVisual.GetVisualRoot(); // Get the root control and its scaling var scaling = new Vector(root.RenderScaling, root.RenderScaling); // Create a matrix to translate from control coordinates to device coordinates. var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling); if (m == null) return p; // Translate the point to device coordinates. var devicePoint = p.Transform(m.Value); // Snap the coordinate to the midpoint between device pixels. devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5); // Translate the point back to control coordinates. var inv = m.Value.Invert(); Point result = devicePoint.Transform(inv); return result; } #endregion public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj) { while (obj != null) { yield return obj; if (obj is Visual v) { obj = (AvaloniaObject)v.GetVisualParent(); } else { break; } } } public static IEnumerable<char> AsEnumerable(this string s) { // ReSharper disable once ForCanBeConvertedToForeach for (var i = 0; i < s.Length; i++) { yield return s[i]; } } [Conditional("DEBUG")] public static void CheckIsFrozen(object o) { if (o is IFreezable f && !f.IsFrozen) Debug.WriteLine("Performance warning: Not frozen: " + f); } [Conditional("DEBUG")] public static void Log(bool condition, string format, params object[] args) { if (condition) { string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace; //Console.WriteLine(output); Debug.WriteLine(output); } } public static bool CapturePointer(this IInputElement element, IPointer device) { device.Capture(element); return device.Captured == element; } public static void ReleasePointerCapture(this IInputElement element, IPointer device) { if (element == device.Captured) { device.Capture(null); } } public static T PeekOrDefault<T>(this ImmutableStack<T> stack) { return stack.IsEmpty ? default(T) : stack.Peek(); } } } <MSG> remove whitespace. <DFF> @@ -178,8 +178,7 @@ namespace AvaloniaEdit.Utils #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { - return new System.Drawing.Point((int)p.X, (int)p.Y); - + return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p)
1
remove whitespace.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062673
<NME> ExtensionMethods.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Xml; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Input; using Avalonia.Media; using Avalonia.VisualTree; namespace AvaloniaEdit.Utils { public static class ExtensionMethods { #region Epsilon / IsClose / CoerceValue /// <summary> /// Epsilon used for <c>IsClose()</c> implementations. /// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin), /// and there's no need to be too accurate (we're dealing with pixels here), /// so we will use the value 0.01. /// Previosly we used 1e-8 but that was causing issues: /// https://community.sharpdevelop.net/forums/t/16048.aspx /// </summary> public const double Epsilon = 0.01; /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this double d1, double d2) { // ReSharper disable once CompareOfFloatsByEqualityOperator if (d1 == d2) // required for infinities return true; return Math.Abs(d1 - d2) < Epsilon; } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Size d1, Size d2) { return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height); } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Vector d1, Vector d2) { return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static double CoerceValue(this double value, double minimum, double maximum) { return Math.Max(Math.Min(value, maximum), minimum); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static int CoerceValue(this int value, int minimum, int maximum) { return Math.Max(Math.Min(value, maximum), minimum); } #endregion #region CreateTypeface /// <summary> /// Creates typeface from the framework element. /// </summary> public static Typeface CreateTypeface(this Control fe) { return new Typeface(fe.GetValue(TextElement.FontFamilyProperty), fe.GetValue(TextElement.FontStyleProperty), fe.GetValue(TextElement.FontWeightProperty), fe.GetValue(TextElement.FontStretchProperty)); } #endregion #region AddRange / Sequence public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements) { foreach (T e in elements) collection.Add(e); } /// <summary> /// Creates an IEnumerable with a single value. /// </summary> public static IEnumerable<T> Sequence<T>(T value) { yield return value; } #endregion #region XML reading ///// <summary> ///// Gets the value of the attribute, or null if the attribute does not exist. ///// </summary> //public static string GetAttributeOrNull(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? attr.Value : null; //} ///// <summary> ///// Gets the value of the attribute as boolean, or null if the attribute does not exist. ///// </summary> //public static bool? GetBoolAttribute(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null; //} /// <summary> /// Gets the value of the attribute as boolean, or null if the attribute does not exist. /// </summary> public static bool? GetBoolAttribute(this XmlReader reader, string attributeName) { string attributeValue = reader.GetAttribute(attributeName); if (attributeValue == null) return null; else return XmlConvert.ToBoolean(attributeValue); } #endregion #region DPI independence //public static Rect TransformToDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return Rect.Transform(rect, matrix); //} //public static Rect TransformFromDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return Rect.Transform(rect, matrix); //} //public static Size TransformToDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return new Size(size.Width * matrix.M11, size.Height * matrix.M22); //} //public static Size TransformFromDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) //} //public static Point TransformFromDevice(this Point point, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return new Point(point.X * matrix.M11, point.Y * matrix.M22); //} #endregion #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) { return new Point(p.X, p.Y); } public static Size ToAvalonia(this System.Drawing.Size s) { return new Size(s.Width, s.Height); } public static Rect ToAvalonia(this System.Drawing.Rectangle rect) { return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia()); } #endregion #region Snap to device pixels public static Point SnapToDevicePixels(this Point p, IVisual targetVisual) { var root = targetVisual.GetVisualRoot(); // Get the root control and its scaling var scaling = new Vector(root.RenderScaling, root.RenderScaling); // Create a matrix to translate from control coordinates to device coordinates. var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling); if (m == null) return p; // Translate the point to device coordinates. var devicePoint = p.Transform(m.Value); // Snap the coordinate to the midpoint between device pixels. devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5); // Translate the point back to control coordinates. var inv = m.Value.Invert(); Point result = devicePoint.Transform(inv); return result; } #endregion public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj) { while (obj != null) { yield return obj; if (obj is Visual v) { obj = (AvaloniaObject)v.GetVisualParent(); } else { break; } } } public static IEnumerable<char> AsEnumerable(this string s) { // ReSharper disable once ForCanBeConvertedToForeach for (var i = 0; i < s.Length; i++) { yield return s[i]; } } [Conditional("DEBUG")] public static void CheckIsFrozen(object o) { if (o is IFreezable f && !f.IsFrozen) Debug.WriteLine("Performance warning: Not frozen: " + f); } [Conditional("DEBUG")] public static void Log(bool condition, string format, params object[] args) { if (condition) { string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace; //Console.WriteLine(output); Debug.WriteLine(output); } } public static bool CapturePointer(this IInputElement element, IPointer device) { device.Capture(element); return device.Captured == element; } public static void ReleasePointerCapture(this IInputElement element, IPointer device) { if (element == device.Captured) { device.Capture(null); } } public static T PeekOrDefault<T>(this ImmutableStack<T> stack) { return stack.IsEmpty ? default(T) : stack.Peek(); } } } <MSG> remove whitespace. <DFF> @@ -178,8 +178,7 @@ namespace AvaloniaEdit.Utils #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { - return new System.Drawing.Point((int)p.X, (int)p.Y); - + return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p)
1
remove whitespace.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062674
<NME> ExtensionMethods.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Xml; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Input; using Avalonia.Media; using Avalonia.VisualTree; namespace AvaloniaEdit.Utils { public static class ExtensionMethods { #region Epsilon / IsClose / CoerceValue /// <summary> /// Epsilon used for <c>IsClose()</c> implementations. /// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin), /// and there's no need to be too accurate (we're dealing with pixels here), /// so we will use the value 0.01. /// Previosly we used 1e-8 but that was causing issues: /// https://community.sharpdevelop.net/forums/t/16048.aspx /// </summary> public const double Epsilon = 0.01; /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this double d1, double d2) { // ReSharper disable once CompareOfFloatsByEqualityOperator if (d1 == d2) // required for infinities return true; return Math.Abs(d1 - d2) < Epsilon; } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Size d1, Size d2) { return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height); } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Vector d1, Vector d2) { return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static double CoerceValue(this double value, double minimum, double maximum) { return Math.Max(Math.Min(value, maximum), minimum); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static int CoerceValue(this int value, int minimum, int maximum) { return Math.Max(Math.Min(value, maximum), minimum); } #endregion #region CreateTypeface /// <summary> /// Creates typeface from the framework element. /// </summary> public static Typeface CreateTypeface(this Control fe) { return new Typeface(fe.GetValue(TextElement.FontFamilyProperty), fe.GetValue(TextElement.FontStyleProperty), fe.GetValue(TextElement.FontWeightProperty), fe.GetValue(TextElement.FontStretchProperty)); } #endregion #region AddRange / Sequence public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements) { foreach (T e in elements) collection.Add(e); } /// <summary> /// Creates an IEnumerable with a single value. /// </summary> public static IEnumerable<T> Sequence<T>(T value) { yield return value; } #endregion #region XML reading ///// <summary> ///// Gets the value of the attribute, or null if the attribute does not exist. ///// </summary> //public static string GetAttributeOrNull(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? attr.Value : null; //} ///// <summary> ///// Gets the value of the attribute as boolean, or null if the attribute does not exist. ///// </summary> //public static bool? GetBoolAttribute(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null; //} /// <summary> /// Gets the value of the attribute as boolean, or null if the attribute does not exist. /// </summary> public static bool? GetBoolAttribute(this XmlReader reader, string attributeName) { string attributeValue = reader.GetAttribute(attributeName); if (attributeValue == null) return null; else return XmlConvert.ToBoolean(attributeValue); } #endregion #region DPI independence //public static Rect TransformToDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return Rect.Transform(rect, matrix); //} //public static Rect TransformFromDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return Rect.Transform(rect, matrix); //} //public static Size TransformToDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return new Size(size.Width * matrix.M11, size.Height * matrix.M22); //} //public static Size TransformFromDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) //} //public static Point TransformFromDevice(this Point point, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return new Point(point.X * matrix.M11, point.Y * matrix.M22); //} #endregion #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) { return new Point(p.X, p.Y); } public static Size ToAvalonia(this System.Drawing.Size s) { return new Size(s.Width, s.Height); } public static Rect ToAvalonia(this System.Drawing.Rectangle rect) { return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia()); } #endregion #region Snap to device pixels public static Point SnapToDevicePixels(this Point p, IVisual targetVisual) { var root = targetVisual.GetVisualRoot(); // Get the root control and its scaling var scaling = new Vector(root.RenderScaling, root.RenderScaling); // Create a matrix to translate from control coordinates to device coordinates. var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling); if (m == null) return p; // Translate the point to device coordinates. var devicePoint = p.Transform(m.Value); // Snap the coordinate to the midpoint between device pixels. devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5); // Translate the point back to control coordinates. var inv = m.Value.Invert(); Point result = devicePoint.Transform(inv); return result; } #endregion public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj) { while (obj != null) { yield return obj; if (obj is Visual v) { obj = (AvaloniaObject)v.GetVisualParent(); } else { break; } } } public static IEnumerable<char> AsEnumerable(this string s) { // ReSharper disable once ForCanBeConvertedToForeach for (var i = 0; i < s.Length; i++) { yield return s[i]; } } [Conditional("DEBUG")] public static void CheckIsFrozen(object o) { if (o is IFreezable f && !f.IsFrozen) Debug.WriteLine("Performance warning: Not frozen: " + f); } [Conditional("DEBUG")] public static void Log(bool condition, string format, params object[] args) { if (condition) { string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace; //Console.WriteLine(output); Debug.WriteLine(output); } } public static bool CapturePointer(this IInputElement element, IPointer device) { device.Capture(element); return device.Captured == element; } public static void ReleasePointerCapture(this IInputElement element, IPointer device) { if (element == device.Captured) { device.Capture(null); } } public static T PeekOrDefault<T>(this ImmutableStack<T> stack) { return stack.IsEmpty ? default(T) : stack.Peek(); } } } <MSG> remove whitespace. <DFF> @@ -178,8 +178,7 @@ namespace AvaloniaEdit.Utils #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { - return new System.Drawing.Point((int)p.X, (int)p.Y); - + return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p)
1
remove whitespace.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062675
<NME> ExtensionMethods.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Xml; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Input; using Avalonia.Media; using Avalonia.VisualTree; namespace AvaloniaEdit.Utils { public static class ExtensionMethods { #region Epsilon / IsClose / CoerceValue /// <summary> /// Epsilon used for <c>IsClose()</c> implementations. /// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin), /// and there's no need to be too accurate (we're dealing with pixels here), /// so we will use the value 0.01. /// Previosly we used 1e-8 but that was causing issues: /// https://community.sharpdevelop.net/forums/t/16048.aspx /// </summary> public const double Epsilon = 0.01; /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this double d1, double d2) { // ReSharper disable once CompareOfFloatsByEqualityOperator if (d1 == d2) // required for infinities return true; return Math.Abs(d1 - d2) < Epsilon; } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Size d1, Size d2) { return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height); } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Vector d1, Vector d2) { return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static double CoerceValue(this double value, double minimum, double maximum) { return Math.Max(Math.Min(value, maximum), minimum); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static int CoerceValue(this int value, int minimum, int maximum) { return Math.Max(Math.Min(value, maximum), minimum); } #endregion #region CreateTypeface /// <summary> /// Creates typeface from the framework element. /// </summary> public static Typeface CreateTypeface(this Control fe) { return new Typeface(fe.GetValue(TextElement.FontFamilyProperty), fe.GetValue(TextElement.FontStyleProperty), fe.GetValue(TextElement.FontWeightProperty), fe.GetValue(TextElement.FontStretchProperty)); } #endregion #region AddRange / Sequence public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements) { foreach (T e in elements) collection.Add(e); } /// <summary> /// Creates an IEnumerable with a single value. /// </summary> public static IEnumerable<T> Sequence<T>(T value) { yield return value; } #endregion #region XML reading ///// <summary> ///// Gets the value of the attribute, or null if the attribute does not exist. ///// </summary> //public static string GetAttributeOrNull(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? attr.Value : null; //} ///// <summary> ///// Gets the value of the attribute as boolean, or null if the attribute does not exist. ///// </summary> //public static bool? GetBoolAttribute(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null; //} /// <summary> /// Gets the value of the attribute as boolean, or null if the attribute does not exist. /// </summary> public static bool? GetBoolAttribute(this XmlReader reader, string attributeName) { string attributeValue = reader.GetAttribute(attributeName); if (attributeValue == null) return null; else return XmlConvert.ToBoolean(attributeValue); } #endregion #region DPI independence //public static Rect TransformToDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return Rect.Transform(rect, matrix); //} //public static Rect TransformFromDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return Rect.Transform(rect, matrix); //} //public static Size TransformToDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return new Size(size.Width * matrix.M11, size.Height * matrix.M22); //} //public static Size TransformFromDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) //} //public static Point TransformFromDevice(this Point point, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return new Point(point.X * matrix.M11, point.Y * matrix.M22); //} #endregion #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) { return new Point(p.X, p.Y); } public static Size ToAvalonia(this System.Drawing.Size s) { return new Size(s.Width, s.Height); } public static Rect ToAvalonia(this System.Drawing.Rectangle rect) { return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia()); } #endregion #region Snap to device pixels public static Point SnapToDevicePixels(this Point p, IVisual targetVisual) { var root = targetVisual.GetVisualRoot(); // Get the root control and its scaling var scaling = new Vector(root.RenderScaling, root.RenderScaling); // Create a matrix to translate from control coordinates to device coordinates. var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling); if (m == null) return p; // Translate the point to device coordinates. var devicePoint = p.Transform(m.Value); // Snap the coordinate to the midpoint between device pixels. devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5); // Translate the point back to control coordinates. var inv = m.Value.Invert(); Point result = devicePoint.Transform(inv); return result; } #endregion public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj) { while (obj != null) { yield return obj; if (obj is Visual v) { obj = (AvaloniaObject)v.GetVisualParent(); } else { break; } } } public static IEnumerable<char> AsEnumerable(this string s) { // ReSharper disable once ForCanBeConvertedToForeach for (var i = 0; i < s.Length; i++) { yield return s[i]; } } [Conditional("DEBUG")] public static void CheckIsFrozen(object o) { if (o is IFreezable f && !f.IsFrozen) Debug.WriteLine("Performance warning: Not frozen: " + f); } [Conditional("DEBUG")] public static void Log(bool condition, string format, params object[] args) { if (condition) { string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace; //Console.WriteLine(output); Debug.WriteLine(output); } } public static bool CapturePointer(this IInputElement element, IPointer device) { device.Capture(element); return device.Captured == element; } public static void ReleasePointerCapture(this IInputElement element, IPointer device) { if (element == device.Captured) { device.Capture(null); } } public static T PeekOrDefault<T>(this ImmutableStack<T> stack) { return stack.IsEmpty ? default(T) : stack.Peek(); } } } <MSG> remove whitespace. <DFF> @@ -178,8 +178,7 @@ namespace AvaloniaEdit.Utils #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { - return new System.Drawing.Point((int)p.X, (int)p.Y); - + return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p)
1
remove whitespace.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062676
<NME> ExtensionMethods.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Xml; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Input; using Avalonia.Media; using Avalonia.VisualTree; namespace AvaloniaEdit.Utils { public static class ExtensionMethods { #region Epsilon / IsClose / CoerceValue /// <summary> /// Epsilon used for <c>IsClose()</c> implementations. /// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin), /// and there's no need to be too accurate (we're dealing with pixels here), /// so we will use the value 0.01. /// Previosly we used 1e-8 but that was causing issues: /// https://community.sharpdevelop.net/forums/t/16048.aspx /// </summary> public const double Epsilon = 0.01; /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this double d1, double d2) { // ReSharper disable once CompareOfFloatsByEqualityOperator if (d1 == d2) // required for infinities return true; return Math.Abs(d1 - d2) < Epsilon; } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Size d1, Size d2) { return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height); } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Vector d1, Vector d2) { return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static double CoerceValue(this double value, double minimum, double maximum) { return Math.Max(Math.Min(value, maximum), minimum); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static int CoerceValue(this int value, int minimum, int maximum) { return Math.Max(Math.Min(value, maximum), minimum); } #endregion #region CreateTypeface /// <summary> /// Creates typeface from the framework element. /// </summary> public static Typeface CreateTypeface(this Control fe) { return new Typeface(fe.GetValue(TextElement.FontFamilyProperty), fe.GetValue(TextElement.FontStyleProperty), fe.GetValue(TextElement.FontWeightProperty), fe.GetValue(TextElement.FontStretchProperty)); } #endregion #region AddRange / Sequence public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements) { foreach (T e in elements) collection.Add(e); } /// <summary> /// Creates an IEnumerable with a single value. /// </summary> public static IEnumerable<T> Sequence<T>(T value) { yield return value; } #endregion #region XML reading ///// <summary> ///// Gets the value of the attribute, or null if the attribute does not exist. ///// </summary> //public static string GetAttributeOrNull(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? attr.Value : null; //} ///// <summary> ///// Gets the value of the attribute as boolean, or null if the attribute does not exist. ///// </summary> //public static bool? GetBoolAttribute(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null; //} /// <summary> /// Gets the value of the attribute as boolean, or null if the attribute does not exist. /// </summary> public static bool? GetBoolAttribute(this XmlReader reader, string attributeName) { string attributeValue = reader.GetAttribute(attributeName); if (attributeValue == null) return null; else return XmlConvert.ToBoolean(attributeValue); } #endregion #region DPI independence //public static Rect TransformToDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return Rect.Transform(rect, matrix); //} //public static Rect TransformFromDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return Rect.Transform(rect, matrix); //} //public static Size TransformToDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return new Size(size.Width * matrix.M11, size.Height * matrix.M22); //} //public static Size TransformFromDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) //} //public static Point TransformFromDevice(this Point point, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return new Point(point.X * matrix.M11, point.Y * matrix.M22); //} #endregion #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) { return new Point(p.X, p.Y); } public static Size ToAvalonia(this System.Drawing.Size s) { return new Size(s.Width, s.Height); } public static Rect ToAvalonia(this System.Drawing.Rectangle rect) { return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia()); } #endregion #region Snap to device pixels public static Point SnapToDevicePixels(this Point p, IVisual targetVisual) { var root = targetVisual.GetVisualRoot(); // Get the root control and its scaling var scaling = new Vector(root.RenderScaling, root.RenderScaling); // Create a matrix to translate from control coordinates to device coordinates. var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling); if (m == null) return p; // Translate the point to device coordinates. var devicePoint = p.Transform(m.Value); // Snap the coordinate to the midpoint between device pixels. devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5); // Translate the point back to control coordinates. var inv = m.Value.Invert(); Point result = devicePoint.Transform(inv); return result; } #endregion public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj) { while (obj != null) { yield return obj; if (obj is Visual v) { obj = (AvaloniaObject)v.GetVisualParent(); } else { break; } } } public static IEnumerable<char> AsEnumerable(this string s) { // ReSharper disable once ForCanBeConvertedToForeach for (var i = 0; i < s.Length; i++) { yield return s[i]; } } [Conditional("DEBUG")] public static void CheckIsFrozen(object o) { if (o is IFreezable f && !f.IsFrozen) Debug.WriteLine("Performance warning: Not frozen: " + f); } [Conditional("DEBUG")] public static void Log(bool condition, string format, params object[] args) { if (condition) { string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace; //Console.WriteLine(output); Debug.WriteLine(output); } } public static bool CapturePointer(this IInputElement element, IPointer device) { device.Capture(element); return device.Captured == element; } public static void ReleasePointerCapture(this IInputElement element, IPointer device) { if (element == device.Captured) { device.Capture(null); } } public static T PeekOrDefault<T>(this ImmutableStack<T> stack) { return stack.IsEmpty ? default(T) : stack.Peek(); } } } <MSG> remove whitespace. <DFF> @@ -178,8 +178,7 @@ namespace AvaloniaEdit.Utils #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { - return new System.Drawing.Point((int)p.X, (int)p.Y); - + return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p)
1
remove whitespace.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062677
<NME> ExtensionMethods.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Xml; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Input; using Avalonia.Media; using Avalonia.VisualTree; namespace AvaloniaEdit.Utils { public static class ExtensionMethods { #region Epsilon / IsClose / CoerceValue /// <summary> /// Epsilon used for <c>IsClose()</c> implementations. /// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin), /// and there's no need to be too accurate (we're dealing with pixels here), /// so we will use the value 0.01. /// Previosly we used 1e-8 but that was causing issues: /// https://community.sharpdevelop.net/forums/t/16048.aspx /// </summary> public const double Epsilon = 0.01; /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this double d1, double d2) { // ReSharper disable once CompareOfFloatsByEqualityOperator if (d1 == d2) // required for infinities return true; return Math.Abs(d1 - d2) < Epsilon; } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Size d1, Size d2) { return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height); } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Vector d1, Vector d2) { return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static double CoerceValue(this double value, double minimum, double maximum) { return Math.Max(Math.Min(value, maximum), minimum); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static int CoerceValue(this int value, int minimum, int maximum) { return Math.Max(Math.Min(value, maximum), minimum); } #endregion #region CreateTypeface /// <summary> /// Creates typeface from the framework element. /// </summary> public static Typeface CreateTypeface(this Control fe) { return new Typeface(fe.GetValue(TextElement.FontFamilyProperty), fe.GetValue(TextElement.FontStyleProperty), fe.GetValue(TextElement.FontWeightProperty), fe.GetValue(TextElement.FontStretchProperty)); } #endregion #region AddRange / Sequence public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements) { foreach (T e in elements) collection.Add(e); } /// <summary> /// Creates an IEnumerable with a single value. /// </summary> public static IEnumerable<T> Sequence<T>(T value) { yield return value; } #endregion #region XML reading ///// <summary> ///// Gets the value of the attribute, or null if the attribute does not exist. ///// </summary> //public static string GetAttributeOrNull(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? attr.Value : null; //} ///// <summary> ///// Gets the value of the attribute as boolean, or null if the attribute does not exist. ///// </summary> //public static bool? GetBoolAttribute(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null; //} /// <summary> /// Gets the value of the attribute as boolean, or null if the attribute does not exist. /// </summary> public static bool? GetBoolAttribute(this XmlReader reader, string attributeName) { string attributeValue = reader.GetAttribute(attributeName); if (attributeValue == null) return null; else return XmlConvert.ToBoolean(attributeValue); } #endregion #region DPI independence //public static Rect TransformToDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return Rect.Transform(rect, matrix); //} //public static Rect TransformFromDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return Rect.Transform(rect, matrix); //} //public static Size TransformToDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return new Size(size.Width * matrix.M11, size.Height * matrix.M22); //} //public static Size TransformFromDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) //} //public static Point TransformFromDevice(this Point point, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return new Point(point.X * matrix.M11, point.Y * matrix.M22); //} #endregion #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) { return new Point(p.X, p.Y); } public static Size ToAvalonia(this System.Drawing.Size s) { return new Size(s.Width, s.Height); } public static Rect ToAvalonia(this System.Drawing.Rectangle rect) { return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia()); } #endregion #region Snap to device pixels public static Point SnapToDevicePixels(this Point p, IVisual targetVisual) { var root = targetVisual.GetVisualRoot(); // Get the root control and its scaling var scaling = new Vector(root.RenderScaling, root.RenderScaling); // Create a matrix to translate from control coordinates to device coordinates. var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling); if (m == null) return p; // Translate the point to device coordinates. var devicePoint = p.Transform(m.Value); // Snap the coordinate to the midpoint between device pixels. devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5); // Translate the point back to control coordinates. var inv = m.Value.Invert(); Point result = devicePoint.Transform(inv); return result; } #endregion public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj) { while (obj != null) { yield return obj; if (obj is Visual v) { obj = (AvaloniaObject)v.GetVisualParent(); } else { break; } } } public static IEnumerable<char> AsEnumerable(this string s) { // ReSharper disable once ForCanBeConvertedToForeach for (var i = 0; i < s.Length; i++) { yield return s[i]; } } [Conditional("DEBUG")] public static void CheckIsFrozen(object o) { if (o is IFreezable f && !f.IsFrozen) Debug.WriteLine("Performance warning: Not frozen: " + f); } [Conditional("DEBUG")] public static void Log(bool condition, string format, params object[] args) { if (condition) { string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace; //Console.WriteLine(output); Debug.WriteLine(output); } } public static bool CapturePointer(this IInputElement element, IPointer device) { device.Capture(element); return device.Captured == element; } public static void ReleasePointerCapture(this IInputElement element, IPointer device) { if (element == device.Captured) { device.Capture(null); } } public static T PeekOrDefault<T>(this ImmutableStack<T> stack) { return stack.IsEmpty ? default(T) : stack.Peek(); } } } <MSG> remove whitespace. <DFF> @@ -178,8 +178,7 @@ namespace AvaloniaEdit.Utils #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { - return new System.Drawing.Point((int)p.X, (int)p.Y); - + return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p)
1
remove whitespace.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062678
<NME> ExtensionMethods.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Xml; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Input; using Avalonia.Media; using Avalonia.VisualTree; namespace AvaloniaEdit.Utils { public static class ExtensionMethods { #region Epsilon / IsClose / CoerceValue /// <summary> /// Epsilon used for <c>IsClose()</c> implementations. /// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin), /// and there's no need to be too accurate (we're dealing with pixels here), /// so we will use the value 0.01. /// Previosly we used 1e-8 but that was causing issues: /// https://community.sharpdevelop.net/forums/t/16048.aspx /// </summary> public const double Epsilon = 0.01; /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this double d1, double d2) { // ReSharper disable once CompareOfFloatsByEqualityOperator if (d1 == d2) // required for infinities return true; return Math.Abs(d1 - d2) < Epsilon; } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Size d1, Size d2) { return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height); } /// <summary> /// Returns true if the doubles are close (difference smaller than 0.01). /// </summary> public static bool IsClose(this Vector d1, Vector d2) { return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static double CoerceValue(this double value, double minimum, double maximum) { return Math.Max(Math.Min(value, maximum), minimum); } /// <summary> /// Forces the value to stay between mininum and maximum. /// </summary> /// <returns>minimum, if value is less than minimum. /// Maximum, if value is greater than maximum. /// Otherwise, value.</returns> public static int CoerceValue(this int value, int minimum, int maximum) { return Math.Max(Math.Min(value, maximum), minimum); } #endregion #region CreateTypeface /// <summary> /// Creates typeface from the framework element. /// </summary> public static Typeface CreateTypeface(this Control fe) { return new Typeface(fe.GetValue(TextElement.FontFamilyProperty), fe.GetValue(TextElement.FontStyleProperty), fe.GetValue(TextElement.FontWeightProperty), fe.GetValue(TextElement.FontStretchProperty)); } #endregion #region AddRange / Sequence public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements) { foreach (T e in elements) collection.Add(e); } /// <summary> /// Creates an IEnumerable with a single value. /// </summary> public static IEnumerable<T> Sequence<T>(T value) { yield return value; } #endregion #region XML reading ///// <summary> ///// Gets the value of the attribute, or null if the attribute does not exist. ///// </summary> //public static string GetAttributeOrNull(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? attr.Value : null; //} ///// <summary> ///// Gets the value of the attribute as boolean, or null if the attribute does not exist. ///// </summary> //public static bool? GetBoolAttribute(this XmlElement element, string attributeName) //{ // XmlAttribute attr = element.GetAttributeNode(attributeName); // return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null; //} /// <summary> /// Gets the value of the attribute as boolean, or null if the attribute does not exist. /// </summary> public static bool? GetBoolAttribute(this XmlReader reader, string attributeName) { string attributeValue = reader.GetAttribute(attributeName); if (attributeValue == null) return null; else return XmlConvert.ToBoolean(attributeValue); } #endregion #region DPI independence //public static Rect TransformToDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return Rect.Transform(rect, matrix); //} //public static Rect TransformFromDevice(this Rect rect, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return Rect.Transform(rect, matrix); //} //public static Size TransformToDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; // return new Size(size.Width * matrix.M11, size.Height * matrix.M22); //} //public static Size TransformFromDevice(this Size size, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) //} //public static Point TransformFromDevice(this Point point, Visual visual) //{ // Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; // return new Point(point.X * matrix.M11, point.Y * matrix.M22); //} #endregion #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p) { return new Point(p.X, p.Y); } public static Size ToAvalonia(this System.Drawing.Size s) { return new Size(s.Width, s.Height); } public static Rect ToAvalonia(this System.Drawing.Rectangle rect) { return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia()); } #endregion #region Snap to device pixels public static Point SnapToDevicePixels(this Point p, IVisual targetVisual) { var root = targetVisual.GetVisualRoot(); // Get the root control and its scaling var scaling = new Vector(root.RenderScaling, root.RenderScaling); // Create a matrix to translate from control coordinates to device coordinates. var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling); if (m == null) return p; // Translate the point to device coordinates. var devicePoint = p.Transform(m.Value); // Snap the coordinate to the midpoint between device pixels. devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5); // Translate the point back to control coordinates. var inv = m.Value.Invert(); Point result = devicePoint.Transform(inv); return result; } #endregion public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj) { while (obj != null) { yield return obj; if (obj is Visual v) { obj = (AvaloniaObject)v.GetVisualParent(); } else { break; } } } public static IEnumerable<char> AsEnumerable(this string s) { // ReSharper disable once ForCanBeConvertedToForeach for (var i = 0; i < s.Length; i++) { yield return s[i]; } } [Conditional("DEBUG")] public static void CheckIsFrozen(object o) { if (o is IFreezable f && !f.IsFrozen) Debug.WriteLine("Performance warning: Not frozen: " + f); } [Conditional("DEBUG")] public static void Log(bool condition, string format, params object[] args) { if (condition) { string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace; //Console.WriteLine(output); Debug.WriteLine(output); } } public static bool CapturePointer(this IInputElement element, IPointer device) { device.Capture(element); return device.Captured == element; } public static void ReleasePointerCapture(this IInputElement element, IPointer device) { if (element == device.Captured) { device.Capture(null); } } public static T PeekOrDefault<T>(this ImmutableStack<T> stack) { return stack.IsEmpty ? default(T) : stack.Peek(); } } } <MSG> remove whitespace. <DFF> @@ -178,8 +178,7 @@ namespace AvaloniaEdit.Utils #region System.Drawing <-> Avalonia conversions public static System.Drawing.Point ToSystemDrawing(this Point p) { - return new System.Drawing.Point((int)p.X, (int)p.Y); - + return new System.Drawing.Point((int)p.X, (int)p.Y); } public static Point ToAvalonia(this System.Drawing.Point p)
1
remove whitespace.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062679
<NME> README.md <BEF> # Lumen Passport [![Build Status](https://travis-ci.org/dusterio/lumen-passport.svg)](https://travis-ci.org/dusterio/lumen-passport) [![Code Climate](https://codeclimate.com/github/dusterio/lumen-passport/badges/gpa.svg)](https://codeclimate.com/github/dusterio/lumen-passport/badges) [![Total Downloads](https://poser.pugx.org/dusterio/lumen-passport/d/total.svg)](https://packagist.org/packages/dusterio/lumen-passport) [![Latest Stable Version](https://poser.pugx.org/dusterio/lumen-passport/v/stable.svg)](https://packagist.org/packages/dusterio/lumen-passport) [![Latest Unstable Version](https://poser.pugx.org/dusterio/lumen-passport/v/unstable.svg)](https://packagist.org/packages/dusterio/lumen-passport) [![License](https://poser.pugx.org/dusterio/lumen-passport/license.svg)](https://packagist.org/packages/dusterio/lumen-passport) > Making Laravel Passport work with Lumen ## Introduction It's a simple service provider that makes **Laravel Passport** work with **Lumen**. ## Installation First install [Lumen Micro-Framework](https://github.com/laravel/lumen) if you don't have it yet. Then install **Lumen Passport**: ```bash composer require dusterio/lumen-passport ``` Or if you prefer, edit `composer.json` manually and run then `composer update`: ```json { "require": { "dusterio/lumen-passport": "^0.3.5" } } ``` ### Modify the bootstrap flow We need to enable both **Laravel Passport** provider and **Lumen Passport** specific provider: ```php /** @file bootstrap/app.php */ // Enable Facades $app->withFacades(); // Enable Eloquent $app->withEloquent(); // Enable auth middleware (shipped with Lumen) $app->routeMiddleware([ 'auth' => App\Http\Middleware\Authenticate::class, ]); // Register two service providers, Laravel Passport and Lumen adapter $app->register(Laravel\Passport\PassportServiceProvider::class); $app->register(Dusterio\LumenPassport\PassportServiceProvider::class); ``` ### Laravel Passport ^7.3.2 and newer On 30 Jul 2019 [Laravel Passport 7.3.2](https://github.com/laravel/passport/releases/tag/v7.3.2) had a breaking change - new method introduced on Application class that exists in Laravel but not in Lumen. You could either lock in to an older version or swap the Application class like follows: ```php /** @file bootstrap/app.php */ //$app = new Laravel\Lumen\Application( // dirname(__DIR__) //); $app = new \Dusterio\LumenPassport\Lumen7Application( dirname(__DIR__) ); ``` \* _Note: If you look inside this class - all it does is adding an extra method `configurationIsCached()` that always returns `false`._ ### Migrate and install Laravel Passport ```bash # Create new tables for Passport php artisan migrate # Install encryption keys and other stuff for Passport php artisan passport:install ``` It will output the Personal access client ID and secret, and the Password grand client ID and secret. \* _Note: Save the secrets in a safe place, you'll need them later to request the access tokens._ ## Configuration ### Configure Authentication Edit `config/auth.php` to suit your needs. A simple example: ```php /** @file config/auth.php */ return [ 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => \App\Models\User::class ] ], ]; ``` \* _Note: Lumen 7.x and older uses `\App\User::class`_ Load the config since Lumen doesn't load config files automatically: ```php /** @file bootstrap/app.php */ $app->configure('auth'); ``` ### Registering Routes Next, you should call the `LumenPassport::routes` method within the `boot` method of your application (one of your service providers). This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens: ```php /** @file app/Providers/AuthServiceProvider.php */ use Dusterio\LumenPassport\LumenPassport; class AuthServiceProvider extends ServiceProvider { public function boot() { LumenPassport::routes($this->app); /* rest of boot */ } } ``` ### User model Make sure your user model uses **Laravel Passport**'s `HasApiTokens` trait. ```php /** @file app/Models/User.php */ use Laravel\Passport\HasApiTokens; class User extends Model implements AuthenticatableContract, AuthorizableContract { use HasApiTokens, Authenticatable, Authorizable, HasFactory; /* rest of the model */ } ``` ## Usage You'll find all the documentation in [Laravel Passport Docs](https://laravel.com/docs/master/passport). ### Curl example with username and password authentication First you have to [issue an access token](https://laravel.com/docs/master/passport#issuing-access-tokens) and then you can use it to authenticate your requests. ```bash # Request curl --location --request POST '{{APP_URL}}/oauth/token' \ --header 'Content-Type: application/json' \ --data-raw '{ "grant_type": "password", "client_id": "{{CLIENT_ID}}", "client_secret": "{{CLIENT_SECRET}}", "username": "{{USER_EMAIL}}", "password": "{{USER_PASSWORD}}", "scope": "*" }' ``` ```json { "token_type": "Bearer", "expires_in": 31536000, "access_token": "******", "refresh_token": "******" } ``` And with the `access_token` you can request access to the routes that uses the Auth:Api Middleware provided by the **Lumen Passport**. ```php /** @file routes/web.php */ $router->get('/ping', ['middleware' => 'auth', fn () => 'pong']); ``` ```bash # Request curl --location --request GET '{{APP_URL}}/ping' \ --header 'Authorization: Bearer {{ACCESS_TOKEN}}' RewriteRule .* - [e=HTTP_AUTHORIZATION:%1] ``` ## License The MIT License (MIT) POST | /oauth/clients | ClientController | store | auth PUT | /oauth/clients/{client_id} | ClientController | update | auth DELETE | /oauth/clients/{client_id} | ClientController | destroy | auth GET | /oauth/scopes | ScopeController | all | auth GET | /oauth/personal-access-tokens | PersonalAccessTokenController | forUser | auth POST | /oauth/personal-access-tokens | PersonalAccessTokenController | store | auth DELETE | /oauth/personal-access-tokens/{token_id} | PersonalAccessTokenController | destroy | auth \* _Note: some of the **Laravel Passport**'s routes had to 'go away' because they are web-related and rely on sessions (eg. authorise pages). Lumen is an API framework so only API-related routes are present._ ## Extra features There are a couple of extra features that aren't present in **Laravel Passport** ### Prefixing Routes You can add that into an existing group, or add use this route registrar independently like so; ```php /** @file app/Providers/AuthServiceProvider.php */ use Dusterio\LumenPassport\LumenPassport; class AuthServiceProvider extends ServiceProvider { public function boot() { LumenPassport::routes($this->app, ['prefix' => 'v1/oauth']); /* rest of boot */ } } ``` ### Multiple tokens per client Sometimes it's handy to allow multiple access tokens per password grant client. Eg. user logs in from several browsers simultaneously. Currently **Laravel Passport** does not allow that. ```php /** @file app/Providers/AuthServiceProvider.php */ use Dusterio\LumenPassport\LumenPassport; class AuthServiceProvider extends ServiceProvider { public function boot() { LumenPassport::routes($this->app); LumenPassport::allowMultipleTokens(); /* rest of boot */ } } ``` ### Different TTLs for different password clients **Laravel Passport** allows to set one global TTL (time to live) for access tokens, but it may be useful sometimes to set different TTLs for different clients (eg. mobile users get more time than desktop users). Simply do the following in your service provider: ```php /** @file app/Providers/AuthServiceProvider.php */ use Carbon\Carbon; use Dusterio\LumenPassport\LumenPassport; class AuthServiceProvider extends ServiceProvider { public function boot() { LumenPassport::routes($this->app); $client_id = '1'; LumenPassport::tokensExpireIn(Carbon::now()->addDays(14), $client_id); /* rest of boot */ } } ``` If you don't specify client Id, it will simply fall back to Laravel Passport implementation. ### Purge expired tokens ```bash php artisan passport:purge ``` Simply run it to remove expired refresh tokens and their corresponding access tokens from the database. ## Error and issue resolution Instead of opening a new issue, please see if someone has already had it and it has been resolved. If you have found a bug or want to contribute to improving the package, please review the [Contributing guide](https://github.com/dusterio/lumen-passport/blob/master/CONTRIBUTING.md) and the [Code of Conduct](https://github.com/dusterio/lumen-passport/blob/master/CODE_OF_CONDUCT.md). ## Video tutorials I've just started a educational YouTube channel [config.sys](https://www.youtube.com/channel/UCIvUJ1iVRjJP_xL0CD7cMpg) that will cover top IT trends in software development and DevOps. Also I'm happy to announce my newest tool – [GrammarCI](https://www.grammarci.com/), an automated (as a part of CI/CD process) spelling and grammar checks for your code so that your users don't see your typos :) ## License The MIT License (MIT) Copyright (c) 2016 Denis Mysenko Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <MSG> r Advice for 5.6 <DFF> @@ -201,6 +201,17 @@ RewriteCond %{HTTP:Authorization} ^(.*) RewriteRule .* - [e=HTTP_AUTHORIZATION:%1] ``` +## Workaround for Lumen 5.6 + +Lumen 5.6 has a problem resolving HashManager class out of the box - Lumen refuses to resolve 'app' dependency through the +service container. A quick workaround is to add a binding like following in any service provider: + +```php + $this->app->singleton(\Illuminate\Hashing\HashManager::class, function ($app) { + return new \Illuminate\Hashing\HashManager($app); + }); +``` + ## License The MIT License (MIT)
11
r Advice for 5.6
0
.md
md
mit
dusterio/lumen-passport
10062680
<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); if (Document == null) return null; var textView = TextArea.TextView; return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> fix get offset from point, scrollofset needed rounding down. <DFF> @@ -1084,7 +1084,7 @@ namespace AvaloniaEdit if (Document == null) return null; var textView = TextArea.TextView; - return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); + return textView.GetPosition(this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView)); } /// <summary>
1
fix get offset from point, scrollofset needed rounding down.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062681
<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); if (Document == null) return null; var textView = TextArea.TextView; return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> fix get offset from point, scrollofset needed rounding down. <DFF> @@ -1084,7 +1084,7 @@ namespace AvaloniaEdit if (Document == null) return null; var textView = TextArea.TextView; - return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); + return textView.GetPosition(this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView)); } /// <summary>
1
fix get offset from point, scrollofset needed rounding down.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062682
<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); if (Document == null) return null; var textView = TextArea.TextView; return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> fix get offset from point, scrollofset needed rounding down. <DFF> @@ -1084,7 +1084,7 @@ namespace AvaloniaEdit if (Document == null) return null; var textView = TextArea.TextView; - return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); + return textView.GetPosition(this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView)); } /// <summary>
1
fix get offset from point, scrollofset needed rounding down.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062683
<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); if (Document == null) return null; var textView = TextArea.TextView; return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> fix get offset from point, scrollofset needed rounding down. <DFF> @@ -1084,7 +1084,7 @@ namespace AvaloniaEdit if (Document == null) return null; var textView = TextArea.TextView; - return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); + return textView.GetPosition(this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView)); } /// <summary>
1
fix get offset from point, scrollofset needed rounding down.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062684
<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); if (Document == null) return null; var textView = TextArea.TextView; return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> fix get offset from point, scrollofset needed rounding down. <DFF> @@ -1084,7 +1084,7 @@ namespace AvaloniaEdit if (Document == null) return null; var textView = TextArea.TextView; - return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); + return textView.GetPosition(this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView)); } /// <summary>
1
fix get offset from point, scrollofset needed rounding down.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062685
<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); if (Document == null) return null; var textView = TextArea.TextView; return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> fix get offset from point, scrollofset needed rounding down. <DFF> @@ -1084,7 +1084,7 @@ namespace AvaloniaEdit if (Document == null) return null; var textView = TextArea.TextView; - return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); + return textView.GetPosition(this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView)); } /// <summary>
1
fix get offset from point, scrollofset needed rounding down.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062686
<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); if (Document == null) return null; var textView = TextArea.TextView; return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> fix get offset from point, scrollofset needed rounding down. <DFF> @@ -1084,7 +1084,7 @@ namespace AvaloniaEdit if (Document == null) return null; var textView = TextArea.TextView; - return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); + return textView.GetPosition(this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView)); } /// <summary>
1
fix get offset from point, scrollofset needed rounding down.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062687
<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); if (Document == null) return null; var textView = TextArea.TextView; return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> fix get offset from point, scrollofset needed rounding down. <DFF> @@ -1084,7 +1084,7 @@ namespace AvaloniaEdit if (Document == null) return null; var textView = TextArea.TextView; - return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); + return textView.GetPosition(this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView)); } /// <summary>
1
fix get offset from point, scrollofset needed rounding down.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062688
<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); if (Document == null) return null; var textView = TextArea.TextView; return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> fix get offset from point, scrollofset needed rounding down. <DFF> @@ -1084,7 +1084,7 @@ namespace AvaloniaEdit if (Document == null) return null; var textView = TextArea.TextView; - return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); + return textView.GetPosition(this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView)); } /// <summary>
1
fix get offset from point, scrollofset needed rounding down.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062689
<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); if (Document == null) return null; var textView = TextArea.TextView; return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> fix get offset from point, scrollofset needed rounding down. <DFF> @@ -1084,7 +1084,7 @@ namespace AvaloniaEdit if (Document == null) return null; var textView = TextArea.TextView; - return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); + return textView.GetPosition(this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView)); } /// <summary>
1
fix get offset from point, scrollofset needed rounding down.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062690
<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); if (Document == null) return null; var textView = TextArea.TextView; return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> fix get offset from point, scrollofset needed rounding down. <DFF> @@ -1084,7 +1084,7 @@ namespace AvaloniaEdit if (Document == null) return null; var textView = TextArea.TextView; - return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); + return textView.GetPosition(this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView)); } /// <summary>
1
fix get offset from point, scrollofset needed rounding down.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062691
<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); if (Document == null) return null; var textView = TextArea.TextView; return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> fix get offset from point, scrollofset needed rounding down. <DFF> @@ -1084,7 +1084,7 @@ namespace AvaloniaEdit if (Document == null) return null; var textView = TextArea.TextView; - return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); + return textView.GetPosition(this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView)); } /// <summary>
1
fix get offset from point, scrollofset needed rounding down.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062692
<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); if (Document == null) return null; var textView = TextArea.TextView; return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> fix get offset from point, scrollofset needed rounding down. <DFF> @@ -1084,7 +1084,7 @@ namespace AvaloniaEdit if (Document == null) return null; var textView = TextArea.TextView; - return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); + return textView.GetPosition(this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView)); } /// <summary>
1
fix get offset from point, scrollofset needed rounding down.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062693
<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); if (Document == null) return null; var textView = TextArea.TextView; return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> fix get offset from point, scrollofset needed rounding down. <DFF> @@ -1084,7 +1084,7 @@ namespace AvaloniaEdit if (Document == null) return null; var textView = TextArea.TextView; - return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); + return textView.GetPosition(this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView)); } /// <summary>
1
fix get offset from point, scrollofset needed rounding down.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062694
<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); if (Document == null) return null; var textView = TextArea.TextView; return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> fix get offset from point, scrollofset needed rounding down. <DFF> @@ -1084,7 +1084,7 @@ namespace AvaloniaEdit if (Document == null) return null; var textView = TextArea.TextView; - return textView.GetPosition(this.TranslatePoint(point + textView.ScrollOffset, textView)); + return textView.GetPosition(this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView)); } /// <summary>
1
fix get offset from point, scrollofset needed rounding down.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062695
<NME> loadjs.min.js <BEF> !function(n,o){function e(n,o){n=n.push?n:[n];var e,t,r,i,u=[],f=n.length,c=f;for(e=function(n,e){e.length&&u.push(n),c-=1,0===c&&o(u)};f--;)t=n[f],r=l[t],r?e(t,r):(i=d[t]=d[t]||[],i.push(e))}function t(n,o){if(n){var e=d[n];if(l[n]=o,e)for(;e.length;)e[0](n,o),e.splice(0,1)}}function r(n,e){var t=o.createElement("script");t.src=n,t.onload=t.onerror=function(o){var r=t.parentNode;r&&r.removeChild(t),t=null,e(n,o.type)},f.appendChild(t)}function i(n,o){n=n.push?n:[n];var e,t=n.length,i=t,u=[];for(e=function(n,e){"error"===e&&u.push(n),i-=1,0===i&&o(u)};t--;)r(n[t],e)}function u(o,e,r,u){var f,l,d;if(e&&!e.call&&(f=e),l=f?r:e,d=f?u:r,f){if(f in a)throw new Error("LoadJS: Bundle already defined");a[f]=!0}n.setTimeout(function(){i(o,function(n){n.length?(d||c)(n):(l||c)(),t(f,n)})},0)}var f=o.head,c=function(){},a={},l={},d={};u.ready=function(n,o,t){return e(n,function(n){n.length?(t||c)(n):(o||c)()}),u},u.done=function(n){t(n,[])},n.loadjs=u}(window,document); <MSG> removed setTimeout, added examples <DFF> @@ -1,1 +1,1 @@ -!function(n,o){function e(n,o){n=n.push?n:[n];var e,t,r,i,u=[],f=n.length,c=f;for(e=function(n,e){e.length&&u.push(n),c-=1,0===c&&o(u)};f--;)t=n[f],r=l[t],r?e(t,r):(i=d[t]=d[t]||[],i.push(e))}function t(n,o){if(n){var e=d[n];if(l[n]=o,e)for(;e.length;)e[0](n,o),e.splice(0,1)}}function r(n,e){var t=o.createElement("script");t.src=n,t.onload=t.onerror=function(o){var r=t.parentNode;r&&r.removeChild(t),t=null,e(n,o.type)},f.appendChild(t)}function i(n,o){n=n.push?n:[n];var e,t=n.length,i=t,u=[];for(e=function(n,e){"error"===e&&u.push(n),i-=1,0===i&&o(u)};t--;)r(n[t],e)}function u(o,e,r,u){var f,l,d;if(e&&!e.call&&(f=e),l=f?r:e,d=f?u:r,f){if(f in a)throw new Error("LoadJS: Bundle already defined");a[f]=!0}n.setTimeout(function(){i(o,function(n){n.length?(d||c)(n):(l||c)(),t(f,n)})},0)}var f=o.head,c=function(){},a={},l={},d={};u.ready=function(n,o,t){return e(n,function(n){n.length?(t||c)(n):(o||c)()}),u},u.done=function(n){t(n,[])},n.loadjs=u}(window,document); \ No newline at end of file +!function(n,o){function e(n,o){n=n.push?n:[n];var e,r,t,i,u=[],f=n.length,c=f;for(e=function(n,e){e.length&&u.push(n),c-=1,0===c&&o(u)};f--;)r=n[f],t=l[r],t?e(r,t):(i=d[r]=d[r]||[],i.push(e))}function r(n,o){if(n){var e=d[n];if(l[n]=o,e)for(;e.length;)e[0](n,o),e.splice(0,1)}}function t(n,e){var r=o.createElement("script");r.src=n,r.onload=r.onerror=function(o){var t=r.parentNode;t&&t.removeChild(r),r=null,e(n,o.type)},f.appendChild(r)}function i(n,o){n=n.push?n:[n];var e,r=n.length,i=r,u=[];for(e=function(n,e){"error"===e&&u.push(n),i-=1,0===i&&o(u)};r--;)t(n[r],e)}function u(n,o,e,t){var u,f,l;if(o&&!o.call&&(u=o),f=u?e:o,l=u?t:e,u){if(u in a)throw new Error("LoadJS: Bundle already defined");a[u]=!0}i(n,function(n){n.length?(l||c)(n):(f||c)(),r(u,n)})}var f=o.head,c=function(){},a={},l={},d={};u.ready=function(n,o,r){return e(n,function(n){n.length?(r||c)(n):(o||c)()}),u},u.done=function(n){r(n,[])},n.loadjs=u}(window,document); \ No newline at end of file
1
removed setTimeout, added examples
1
.js
min
mit
muicss/loadjs
10062696
<NME> loadjs.min.js <BEF> !function(n,o){function e(n,o){n=n.push?n:[n];var e,t,r,i,u=[],f=n.length,c=f;for(e=function(n,e){e.length&&u.push(n),c-=1,0===c&&o(u)};f--;)t=n[f],r=l[t],r?e(t,r):(i=d[t]=d[t]||[],i.push(e))}function t(n,o){if(n){var e=d[n];if(l[n]=o,e)for(;e.length;)e[0](n,o),e.splice(0,1)}}function r(n,e){var t=o.createElement("script");t.src=n,t.onload=t.onerror=function(o){var r=t.parentNode;r&&r.removeChild(t),t=null,e(n,o.type)},f.appendChild(t)}function i(n,o){n=n.push?n:[n];var e,t=n.length,i=t,u=[];for(e=function(n,e){"error"===e&&u.push(n),i-=1,0===i&&o(u)};t--;)r(n[t],e)}function u(o,e,r,u){var f,l,d;if(e&&!e.call&&(f=e),l=f?r:e,d=f?u:r,f){if(f in a)throw new Error("LoadJS: Bundle already defined");a[f]=!0}n.setTimeout(function(){i(o,function(n){n.length?(d||c)(n):(l||c)(),t(f,n)})},0)}var f=o.head,c=function(){},a={},l={},d={};u.ready=function(n,o,t){return e(n,function(n){n.length?(t||c)(n):(o||c)()}),u},u.done=function(n){t(n,[])},n.loadjs=u}(window,document); <MSG> removed setTimeout, added examples <DFF> @@ -1,1 +1,1 @@ -!function(n,o){function e(n,o){n=n.push?n:[n];var e,t,r,i,u=[],f=n.length,c=f;for(e=function(n,e){e.length&&u.push(n),c-=1,0===c&&o(u)};f--;)t=n[f],r=l[t],r?e(t,r):(i=d[t]=d[t]||[],i.push(e))}function t(n,o){if(n){var e=d[n];if(l[n]=o,e)for(;e.length;)e[0](n,o),e.splice(0,1)}}function r(n,e){var t=o.createElement("script");t.src=n,t.onload=t.onerror=function(o){var r=t.parentNode;r&&r.removeChild(t),t=null,e(n,o.type)},f.appendChild(t)}function i(n,o){n=n.push?n:[n];var e,t=n.length,i=t,u=[];for(e=function(n,e){"error"===e&&u.push(n),i-=1,0===i&&o(u)};t--;)r(n[t],e)}function u(o,e,r,u){var f,l,d;if(e&&!e.call&&(f=e),l=f?r:e,d=f?u:r,f){if(f in a)throw new Error("LoadJS: Bundle already defined");a[f]=!0}n.setTimeout(function(){i(o,function(n){n.length?(d||c)(n):(l||c)(),t(f,n)})},0)}var f=o.head,c=function(){},a={},l={},d={};u.ready=function(n,o,t){return e(n,function(n){n.length?(t||c)(n):(o||c)()}),u},u.done=function(n){t(n,[])},n.loadjs=u}(window,document); \ No newline at end of file +!function(n,o){function e(n,o){n=n.push?n:[n];var e,r,t,i,u=[],f=n.length,c=f;for(e=function(n,e){e.length&&u.push(n),c-=1,0===c&&o(u)};f--;)r=n[f],t=l[r],t?e(r,t):(i=d[r]=d[r]||[],i.push(e))}function r(n,o){if(n){var e=d[n];if(l[n]=o,e)for(;e.length;)e[0](n,o),e.splice(0,1)}}function t(n,e){var r=o.createElement("script");r.src=n,r.onload=r.onerror=function(o){var t=r.parentNode;t&&t.removeChild(r),r=null,e(n,o.type)},f.appendChild(r)}function i(n,o){n=n.push?n:[n];var e,r=n.length,i=r,u=[];for(e=function(n,e){"error"===e&&u.push(n),i-=1,0===i&&o(u)};r--;)t(n[r],e)}function u(n,o,e,t){var u,f,l;if(o&&!o.call&&(u=o),f=u?e:o,l=u?t:e,u){if(u in a)throw new Error("LoadJS: Bundle already defined");a[u]=!0}i(n,function(n){n.length?(l||c)(n):(f||c)(),r(u,n)})}var f=o.head,c=function(){},a={},l={},d={};u.ready=function(n,o,r){return e(n,function(n){n.length?(r||c)(n):(o||c)()}),u},u.done=function(n){r(n,[])},n.loadjs=u}(window,document); \ No newline at end of file
1
removed setTimeout, added examples
1
.js
min
mit
muicss/loadjs
10062697
<NME> theme.css <BEF> .jsgrid-grid-header, .jsgrid-grid-body, .jsgrid-header-row > .jsgrid-header-cell, .jsgrid-filter-row > .jsgrid-cell, .jsgrid-insert-row > .jsgrid-cell, .jsgrid-edit-row > .jsgrid-cell { border: 1px solid #e9e9e9; } .jsgrid-header-row > .jsgrid-header-cell { border-top: 0; } .jsgrid-header-row > .jsgrid-header-cell, .jsgrid-filter-row > .jsgrid-cell, .jsgrid-insert-row > .jsgrid-cell { border-bottom: 0; } .jsgrid-header-row > .jsgrid-header-cell:first-child, border-bottom: none; } .jsgrid-grid-body { border-top: none; } .jsgrid-header-scrollbar::-webkit-scrollbar { visibility: hidden; } .jsgrid-header-scrollbar::-webkit-scrollbar-track { background: #f1f1f1; } .jsgrid-header-sortable:hover { cursor: pointer; background: #fcfcfc; } .jsgrid-header-row .jsgrid-header-sort { background: #c4e2ff; } .jsgrid-header-sort:before { content: " "; display: block; float: left; width: 0; height: 0; border-style: solid; } .jsgrid-header-sort-asc:before { border-width: 0 5px 5px 5px; border-color: transparent transparent #009a67 transparent; } .jsgrid-header-sort-desc:before { border-width: 5px 5px 0 5px; border-color: #009a67 transparent transparent transparent; } .jsgrid-grid-body { border-top: none; } .jsgrid-cell { border: #f3f3f3 1px solid; } .jsgrid-grid-body .jsgrid-row:first-child .jsgrid-cell, .jsgrid-grid-body .jsgrid-alt-row:first-child .jsgrid-cell { border-top: none; } .jsgrid-grid-body .jsgrid-cell:first-child { border-left: none; } .jsgrid-grid-body .jsgrid-cell:last-child { border-right: none; } background-color: transparent; } .jsgrid .jsgrid-mode-button { width: 24px; height: 24px; } .jsgrid-header-row .jsgrid-header-sort-asc { background: url(icons.png) 4px -540px no-repeat #c4e2ff; } .jsgrid-header-row .jsgrid-header-sort-desc { background: url(icons.png) 4px -606px no-repeat #c4e2ff; } .jsgrid-cancel-button { background-position: 0 0; width: 16px; height: 16px; } .jsgrid-clear-filter-button { background-position: 0 -66px; width: 16px; height: 16px; } .jsgrid-delete-button { background-position: 0 -132px; width: 16px; height: 16px; } .jsgrid-edit-button { background-position: 0 -198px; width: 16px; height: 16px; } .jsgrid-insert-mode-button { background-position: 0 -264px; width: 24px; height: 24px; } .jsgrid-insert-button { background-position: 0 -338px; width: 16px; height: 16px; } .jsgrid-search-mode-button { background-position: 0 -404px; width: 24px; height: 24px; } .jsgrid-search-button { background-position: 0 -478px; width: 16px; height: 16px; } .jsgrid-update-button { background-position: 0 -676px; width: 16px; height: 16px; } .jsgrid-selected-row > .jsgrid-cell { background: #c4e2ff; border-color: #c4e2ff; } .jsgrid-nodata-row > .jsgrid-cell { background: #fff; } .jsgrid-invalid input, .jsgrid-invalid select, .jsgrid-invalid textarea { background: #ffe3e5; border: 1px solid #ff808a; } .jsgrid-pager-current-page { font-weight: bold; } .jsgrid-pager-nav-inactive-button a { color: #d3d3d3; } .jsgrid-button + .jsgrid-button { margin-left: 5px; } .jsgrid-button:hover { opacity: .5; transition: opacity 200ms linear; } .jsgrid .jsgrid-button { width: 16px; height: 16px; border: none; cursor: pointer; background-image: url(icons.png); background-repeat: no-repeat; background-color: transparent; } @media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min-device-pixel-ratio: 2) { .jsgrid .jsgrid-button { background-image: url(icons-2x.png); background-size: 24px 352px; } } .jsgrid .jsgrid-mode-button { width: 24px; height: 24px; } .jsgrid-mode-on-button { opacity: .5; } .jsgrid-cancel-edit-button { background-position: 0 0; width: 16px; height: 16px; } .jsgrid-clear-filter-button { background-position: 0 -40px; width: 16px; height: 16px; } .jsgrid-delete-button { background-position: 0 -80px; width: 16px; height: 16px; } .jsgrid-edit-button { background-position: 0 -120px; width: 16px; height: 16px; } .jsgrid-insert-mode-button { background-position: 0 -160px; width: 24px; height: 24px; } .jsgrid-insert-button { background-position: 0 -208px; width: 16px; height: 16px; } .jsgrid-search-mode-button { background-position: 0 -248px; width: 24px; height: 24px; } .jsgrid-search-button { background-position: 0 -296px; width: 16px; height: 16px; } .jsgrid-update-button { background-position: 0 -336px; width: 16px; height: 16px; } .jsgrid-load-shader { background: #ddd; opacity: .5; filter: alpha(opacity=50); } .jsgrid-load-panel { width: 15em; height: 5em; background: #fff; border: 1px solid #e9e9e9; padding-top: 3em; text-align: center; } .jsgrid-load-panel:before { content: ' '; position: absolute; top: .5em; left: 50%; margin-left: -1em; width: 2em; height: 2em; border: 2px solid #009a67; border-right-color: transparent; border-radius: 50%; -webkit-animation: indicator 1s linear infinite; animation: indicator 1s linear infinite; } @-webkit-keyframes indicator { from { -webkit-transform: rotate(0deg); } 50% { -webkit-transform: rotate(180deg); } to { -webkit-transform: rotate(360deg); } } @keyframes indicator { from { transform: rotate(0deg); } 50% { transform: rotate(180deg); } to { transform: rotate(360deg); } } /* old IE */ .jsgrid-load-panel { padding-top: 1.5em\9; } .jsgrid-load-panel:before { display: none\9; } <MSG> Theme: Icons sprite for retina <DFF> @@ -21,6 +21,29 @@ border-bottom: none; } +.jsgrid-header-row .jsgrid-header-sort { + background: #c4e2ff; +} + +.jsgrid-header-sort:before { + content: " "; + display: block; + float: left; + width: 0; + height: 0; + border-style: solid; +} + +.jsgrid-header-sort-asc:before { + border-width: 0 5px 5px 5px; + border-color: transparent transparent #009a67 transparent; +} + +.jsgrid-header-sort-desc:before { + border-width: 5px 5px 0 5px; + border-color: #009a67 transparent transparent transparent; +} + .jsgrid-grid-body { border-top: none; } @@ -85,20 +108,24 @@ background-color: transparent; } +@media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min-device-pixel-ratio: 2) { + .jsgrid .jsgrid-button { + background-image: url(icons-2x.png); + background-size: 24px 352px; + } +} + .jsgrid .jsgrid-mode-button { width: 24px; height: 24px; } -.jsgrid-header-row .jsgrid-header-sort-asc { background: url(icons.png) 4px -540px no-repeat #c4e2ff; } -.jsgrid-header-row .jsgrid-header-sort-desc { background: url(icons.png) 4px -606px no-repeat #c4e2ff; } - .jsgrid-cancel-button { background-position: 0 0; width: 16px; height: 16px; } -.jsgrid-clear-filter-button { background-position: 0 -66px; width: 16px; height: 16px; } -.jsgrid-delete-button { background-position: 0 -132px; width: 16px; height: 16px; } -.jsgrid-edit-button { background-position: 0 -198px; width: 16px; height: 16px; } -.jsgrid-insert-mode-button { background-position: 0 -264px; width: 24px; height: 24px; } -.jsgrid-insert-button { background-position: 0 -338px; width: 16px; height: 16px; } -.jsgrid-search-mode-button { background-position: 0 -404px; width: 24px; height: 24px; } -.jsgrid-search-button { background-position: 0 -478px; width: 16px; height: 16px; } -.jsgrid-update-button { background-position: 0 -676px; width: 16px; height: 16px; } \ No newline at end of file +.jsgrid-clear-filter-button { background-position: 0 -40px; width: 16px; height: 16px; } +.jsgrid-delete-button { background-position: 0 -80px; width: 16px; height: 16px; } +.jsgrid-edit-button { background-position: 0 -120px; width: 16px; height: 16px; } +.jsgrid-insert-mode-button { background-position: 0 -160px; width: 24px; height: 24px; } +.jsgrid-insert-button { background-position: 0 -208px; width: 16px; height: 16px; } +.jsgrid-search-mode-button { background-position: 0 -248px; width: 24px; height: 24px; } +.jsgrid-search-button { background-position: 0 -296px; width: 16px; height: 16px; } +.jsgrid-update-button { background-position: 0 -336px; width: 16px; height: 16px; }
38
Theme: Icons sprite for retina
11
.css
css
mit
tabalinas/jsgrid
10062698
<NME> theme.css <BEF> .jsgrid-grid-header, .jsgrid-grid-body, .jsgrid-header-row > .jsgrid-header-cell, .jsgrid-filter-row > .jsgrid-cell, .jsgrid-insert-row > .jsgrid-cell, .jsgrid-edit-row > .jsgrid-cell { border: 1px solid #e9e9e9; } .jsgrid-header-row > .jsgrid-header-cell { border-top: 0; } .jsgrid-header-row > .jsgrid-header-cell, .jsgrid-filter-row > .jsgrid-cell, .jsgrid-insert-row > .jsgrid-cell { border-bottom: 0; } .jsgrid-header-row > .jsgrid-header-cell:first-child, border-bottom: none; } .jsgrid-grid-body { border-top: none; } .jsgrid-header-scrollbar::-webkit-scrollbar { visibility: hidden; } .jsgrid-header-scrollbar::-webkit-scrollbar-track { background: #f1f1f1; } .jsgrid-header-sortable:hover { cursor: pointer; background: #fcfcfc; } .jsgrid-header-row .jsgrid-header-sort { background: #c4e2ff; } .jsgrid-header-sort:before { content: " "; display: block; float: left; width: 0; height: 0; border-style: solid; } .jsgrid-header-sort-asc:before { border-width: 0 5px 5px 5px; border-color: transparent transparent #009a67 transparent; } .jsgrid-header-sort-desc:before { border-width: 5px 5px 0 5px; border-color: #009a67 transparent transparent transparent; } .jsgrid-grid-body { border-top: none; } .jsgrid-cell { border: #f3f3f3 1px solid; } .jsgrid-grid-body .jsgrid-row:first-child .jsgrid-cell, .jsgrid-grid-body .jsgrid-alt-row:first-child .jsgrid-cell { border-top: none; } .jsgrid-grid-body .jsgrid-cell:first-child { border-left: none; } .jsgrid-grid-body .jsgrid-cell:last-child { border-right: none; } background-color: transparent; } .jsgrid .jsgrid-mode-button { width: 24px; height: 24px; } .jsgrid-header-row .jsgrid-header-sort-asc { background: url(icons.png) 4px -540px no-repeat #c4e2ff; } .jsgrid-header-row .jsgrid-header-sort-desc { background: url(icons.png) 4px -606px no-repeat #c4e2ff; } .jsgrid-cancel-button { background-position: 0 0; width: 16px; height: 16px; } .jsgrid-clear-filter-button { background-position: 0 -66px; width: 16px; height: 16px; } .jsgrid-delete-button { background-position: 0 -132px; width: 16px; height: 16px; } .jsgrid-edit-button { background-position: 0 -198px; width: 16px; height: 16px; } .jsgrid-insert-mode-button { background-position: 0 -264px; width: 24px; height: 24px; } .jsgrid-insert-button { background-position: 0 -338px; width: 16px; height: 16px; } .jsgrid-search-mode-button { background-position: 0 -404px; width: 24px; height: 24px; } .jsgrid-search-button { background-position: 0 -478px; width: 16px; height: 16px; } .jsgrid-update-button { background-position: 0 -676px; width: 16px; height: 16px; } .jsgrid-selected-row > .jsgrid-cell { background: #c4e2ff; border-color: #c4e2ff; } .jsgrid-nodata-row > .jsgrid-cell { background: #fff; } .jsgrid-invalid input, .jsgrid-invalid select, .jsgrid-invalid textarea { background: #ffe3e5; border: 1px solid #ff808a; } .jsgrid-pager-current-page { font-weight: bold; } .jsgrid-pager-nav-inactive-button a { color: #d3d3d3; } .jsgrid-button + .jsgrid-button { margin-left: 5px; } .jsgrid-button:hover { opacity: .5; transition: opacity 200ms linear; } .jsgrid .jsgrid-button { width: 16px; height: 16px; border: none; cursor: pointer; background-image: url(icons.png); background-repeat: no-repeat; background-color: transparent; } @media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min-device-pixel-ratio: 2) { .jsgrid .jsgrid-button { background-image: url(icons-2x.png); background-size: 24px 352px; } } .jsgrid .jsgrid-mode-button { width: 24px; height: 24px; } .jsgrid-mode-on-button { opacity: .5; } .jsgrid-cancel-edit-button { background-position: 0 0; width: 16px; height: 16px; } .jsgrid-clear-filter-button { background-position: 0 -40px; width: 16px; height: 16px; } .jsgrid-delete-button { background-position: 0 -80px; width: 16px; height: 16px; } .jsgrid-edit-button { background-position: 0 -120px; width: 16px; height: 16px; } .jsgrid-insert-mode-button { background-position: 0 -160px; width: 24px; height: 24px; } .jsgrid-insert-button { background-position: 0 -208px; width: 16px; height: 16px; } .jsgrid-search-mode-button { background-position: 0 -248px; width: 24px; height: 24px; } .jsgrid-search-button { background-position: 0 -296px; width: 16px; height: 16px; } .jsgrid-update-button { background-position: 0 -336px; width: 16px; height: 16px; } .jsgrid-load-shader { background: #ddd; opacity: .5; filter: alpha(opacity=50); } .jsgrid-load-panel { width: 15em; height: 5em; background: #fff; border: 1px solid #e9e9e9; padding-top: 3em; text-align: center; } .jsgrid-load-panel:before { content: ' '; position: absolute; top: .5em; left: 50%; margin-left: -1em; width: 2em; height: 2em; border: 2px solid #009a67; border-right-color: transparent; border-radius: 50%; -webkit-animation: indicator 1s linear infinite; animation: indicator 1s linear infinite; } @-webkit-keyframes indicator { from { -webkit-transform: rotate(0deg); } 50% { -webkit-transform: rotate(180deg); } to { -webkit-transform: rotate(360deg); } } @keyframes indicator { from { transform: rotate(0deg); } 50% { transform: rotate(180deg); } to { transform: rotate(360deg); } } /* old IE */ .jsgrid-load-panel { padding-top: 1.5em\9; } .jsgrid-load-panel:before { display: none\9; } <MSG> Theme: Icons sprite for retina <DFF> @@ -21,6 +21,29 @@ border-bottom: none; } +.jsgrid-header-row .jsgrid-header-sort { + background: #c4e2ff; +} + +.jsgrid-header-sort:before { + content: " "; + display: block; + float: left; + width: 0; + height: 0; + border-style: solid; +} + +.jsgrid-header-sort-asc:before { + border-width: 0 5px 5px 5px; + border-color: transparent transparent #009a67 transparent; +} + +.jsgrid-header-sort-desc:before { + border-width: 5px 5px 0 5px; + border-color: #009a67 transparent transparent transparent; +} + .jsgrid-grid-body { border-top: none; } @@ -85,20 +108,24 @@ background-color: transparent; } +@media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min-device-pixel-ratio: 2) { + .jsgrid .jsgrid-button { + background-image: url(icons-2x.png); + background-size: 24px 352px; + } +} + .jsgrid .jsgrid-mode-button { width: 24px; height: 24px; } -.jsgrid-header-row .jsgrid-header-sort-asc { background: url(icons.png) 4px -540px no-repeat #c4e2ff; } -.jsgrid-header-row .jsgrid-header-sort-desc { background: url(icons.png) 4px -606px no-repeat #c4e2ff; } - .jsgrid-cancel-button { background-position: 0 0; width: 16px; height: 16px; } -.jsgrid-clear-filter-button { background-position: 0 -66px; width: 16px; height: 16px; } -.jsgrid-delete-button { background-position: 0 -132px; width: 16px; height: 16px; } -.jsgrid-edit-button { background-position: 0 -198px; width: 16px; height: 16px; } -.jsgrid-insert-mode-button { background-position: 0 -264px; width: 24px; height: 24px; } -.jsgrid-insert-button { background-position: 0 -338px; width: 16px; height: 16px; } -.jsgrid-search-mode-button { background-position: 0 -404px; width: 24px; height: 24px; } -.jsgrid-search-button { background-position: 0 -478px; width: 16px; height: 16px; } -.jsgrid-update-button { background-position: 0 -676px; width: 16px; height: 16px; } \ No newline at end of file +.jsgrid-clear-filter-button { background-position: 0 -40px; width: 16px; height: 16px; } +.jsgrid-delete-button { background-position: 0 -80px; width: 16px; height: 16px; } +.jsgrid-edit-button { background-position: 0 -120px; width: 16px; height: 16px; } +.jsgrid-insert-mode-button { background-position: 0 -160px; width: 24px; height: 24px; } +.jsgrid-insert-button { background-position: 0 -208px; width: 16px; height: 16px; } +.jsgrid-search-mode-button { background-position: 0 -248px; width: 24px; height: 24px; } +.jsgrid-search-button { background-position: 0 -296px; width: 16px; height: 16px; } +.jsgrid-update-button { background-position: 0 -336px; width: 16px; height: 16px; }
38
Theme: Icons sprite for retina
11
.css
css
mit
tabalinas/jsgrid
10062699
<NME> tests.js <BEF> /** * loadjs tests * @module test/tests.js */ var pathsLoaded = null, // file register testEl = null, assert = chai.assert, expect = chai.expect; describe('LoadJS tests', function() { beforeEach(function() { // reset register pathsLoaded = {}; // reset loadjs dependencies loadjs.reset(); }); // ========================================================================== // JavaScript file loading tests // ========================================================================== describe('JavaScript file loading tests', function() { it('should call success callback on valid path', function(done) { loadjs(['assets/file1.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); done(); } }); }); it('should call error callback on invalid path', function(done) { loadjs(['assets/file-doesntexist.js'], { success: function() { throw "Executed success callback"; }, error: function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); } }); }); it('should call success callback on two valid paths', function(done) { loadjs(['assets/file1.js'], { before: function(path, el) { // append to body (instead of head) document.body.appendChild(el); // return `false` to bypass default DOM insertion return false; }, success: function() { assert.equal(pathsLoaded['file1.js'], true); // verify that file was added to body var els = document.body.querySelectorAll('script'), el; for (var i=0; i < els.length; i++) { el = els[i]; if (el.src.indexOf('assets/file1.js') !== -1) done(); } } }); }); it('should call success callback on two valid paths', function(done) { loadjs(['assets/file1.js', 'assets/file2.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }); it('should call error callback on one invalid path', function(done) { loadjs(['assets/file1.js', 'assets/file-doesntexist.js'], { success: function() { throw "Executed success callback"; }, error: function(pathsNotFound) { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); } }); }); it('should support async false', function(done) { this.timeout(5000); var numCompleted = 0, numTests = 20, paths = ['assets/asyncfalse1.js', 'assets/asyncfalse2.js']; // run tests sequentially var testFn = function(paths) { // add cache busters var pathsUncached = paths.slice(0); pathsUncached[0] += '?_=' + Math.random(); pathsUncached[1] += '?_=' + Math.random(); loadjs(pathsUncached, { success: function() { var f1 = paths[0].replace('assets/', ''); var f2 = paths[1].replace('assets/', ''); // check load order assert.isTrue(pathsLoaded[f1]); assert.isFalse(pathsLoaded[f2]); // increment tests numCompleted += 1; if (numCompleted === numTests) { // exit done(); } else { // reset register pathsLoaded = {}; // run test again paths.reverse(); testFn(paths); } }, 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> Merge pull request #29 from toddw/toddw/before-callback Support for `before` callback for before scripts are embedded <DFF> @@ -47,6 +47,34 @@ describe('LoadJS tests', function() { } }); }); + + + 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'); + + done(); + } + }); + }); it('should call success callback on two valid paths', function(done) {
28
Merge pull request #29 from toddw/toddw/before-callback
0
.js
js
mit
muicss/loadjs
10062700
<NME> tests.js <BEF> /** * loadjs tests * @module test/tests.js */ var pathsLoaded = null, // file register testEl = null, assert = chai.assert, expect = chai.expect; describe('LoadJS tests', function() { beforeEach(function() { // reset register pathsLoaded = {}; // reset loadjs dependencies loadjs.reset(); }); // ========================================================================== // JavaScript file loading tests // ========================================================================== describe('JavaScript file loading tests', function() { it('should call success callback on valid path', function(done) { loadjs(['assets/file1.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); done(); } }); }); it('should call error callback on invalid path', function(done) { loadjs(['assets/file-doesntexist.js'], { success: function() { throw "Executed success callback"; }, error: function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); } }); }); it('should call success callback on two valid paths', function(done) { loadjs(['assets/file1.js'], { before: function(path, el) { // append to body (instead of head) document.body.appendChild(el); // return `false` to bypass default DOM insertion return false; }, success: function() { assert.equal(pathsLoaded['file1.js'], true); // verify that file was added to body var els = document.body.querySelectorAll('script'), el; for (var i=0; i < els.length; i++) { el = els[i]; if (el.src.indexOf('assets/file1.js') !== -1) done(); } } }); }); it('should call success callback on two valid paths', function(done) { loadjs(['assets/file1.js', 'assets/file2.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }); it('should call error callback on one invalid path', function(done) { loadjs(['assets/file1.js', 'assets/file-doesntexist.js'], { success: function() { throw "Executed success callback"; }, error: function(pathsNotFound) { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); } }); }); it('should support async false', function(done) { this.timeout(5000); var numCompleted = 0, numTests = 20, paths = ['assets/asyncfalse1.js', 'assets/asyncfalse2.js']; // run tests sequentially var testFn = function(paths) { // add cache busters var pathsUncached = paths.slice(0); pathsUncached[0] += '?_=' + Math.random(); pathsUncached[1] += '?_=' + Math.random(); loadjs(pathsUncached, { success: function() { var f1 = paths[0].replace('assets/', ''); var f2 = paths[1].replace('assets/', ''); // check load order assert.isTrue(pathsLoaded[f1]); assert.isFalse(pathsLoaded[f2]); // increment tests numCompleted += 1; if (numCompleted === numTests) { // exit done(); } else { // reset register pathsLoaded = {}; // run test again paths.reverse(); testFn(paths); } }, 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> Merge pull request #29 from toddw/toddw/before-callback Support for `before` callback for before scripts are embedded <DFF> @@ -47,6 +47,34 @@ describe('LoadJS tests', function() { } }); }); + + + 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'); + + done(); + } + }); + }); it('should call success callback on two valid paths', function(done) {
28
Merge pull request #29 from toddw/toddw/before-callback
0
.js
js
mit
muicss/loadjs
10062701
<NME> jsgrid.css <BEF> .jsgrid { position: relative; overflow: hidden; font-size: 1em; } .jsgrid input, .jsgrid textarea, .jsgrid select { font-size: 1em; } .jsgrid select { font-size: 1em; } .jsgrid-grid-header { overflow-x: hidden; overflow-y: scroll; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none; } .jsgrid-grid-body { overflow-x: auto; overflow-y: scroll; -webkit-overflow-scrolling: touch; } .jsgrid-table { width: 100%; table-layout: fixed; border-collapse: collapse; padding: 0.5em 0.5em; } .jsgrid-table td, .jsgrid-table th { box-sizing: border-box; } .jsgrid-header-cell { box-sizing: border-box; } .jsgrid-align-left { text-align: left; } .jsgrid-align-center, .jsgrid-align-center input, .jsgrid-align-center textarea, .jsgrid-align-center select { text-align: center; padding: .5em .5em; } .jsgrid-filter-row input, .jsgrid-filter-row textarea, .jsgrid-filter-row select, .jsgrid-edit-row input, .jsgrid-edit-row textarea, .jsgrid-edit-row select, .jsgrid-insert-row input, .jsgrid-insert-row textarea, .jsgrid-insert-row select { width: 90%; padding: .3em .5em; } .jsgrid-filter-row select, .jsgrid-edit-row input, .jsgrid-edit-row textarea, .jsgrid-edit-row select, .jsgrid-insert-row input, .jsgrid-insert-row textarea, .jsgrid-insert-row select { width: 100%; padding: .3em .5em; } .jsgrid-filter-row input[type='checkbox'], .jsgrid-edit-row input[type='checkbox'], .jsgrid-insert-row input[type='checkbox'] { width: auto; } .jsgrid-selected-row .jsgrid-cell { cursor: pointer; } .jsgrid-nodata-row .jsgrid-cell { padding: .5em 0; text-align: center; } .jsgrid-header-sort { cursor: pointer; } .jsgrid-pager { padding: .5em 0; } .jsgrid-pager-nav-button { padding: .2em .6em; } .jsgrid-pager-nav-inactive-button { display: none; pointer-events: none; } .jsgrid-pager-page { padding: .2em .6em; } <MSG> Theme: Css code formatting <DFF> @@ -4,7 +4,9 @@ font-size: 1em; } -.jsgrid input, .jsgrid textarea, .jsgrid select { +.jsgrid input, +.jsgrid textarea, +.jsgrid select { font-size: 1em; } @@ -36,7 +38,8 @@ padding: 0.5em 0.5em; } -.jsgrid-table td, .jsgrid-table th { +.jsgrid-table td, +.jsgrid-table th { box-sizing: border-box; } @@ -56,9 +59,15 @@ padding: .5em .5em; } -.jsgrid-filter-row input, .jsgrid-filter-row textarea, .jsgrid-filter-row select, -.jsgrid-edit-row input, .jsgrid-edit-row textarea, .jsgrid-edit-row select, -.jsgrid-insert-row input, .jsgrid-insert-row textarea, .jsgrid-insert-row select { +.jsgrid-filter-row input, +.jsgrid-filter-row textarea, +.jsgrid-filter-row select, +.jsgrid-edit-row input, +.jsgrid-edit-row textarea, +.jsgrid-edit-row select, +.jsgrid-insert-row input, +.jsgrid-insert-row textarea, +.jsgrid-insert-row select { width: 90%; padding: .3em .5em; }
14
Theme: Css code formatting
5
.css
css
mit
tabalinas/jsgrid
10062702
<NME> jsgrid.css <BEF> .jsgrid { position: relative; overflow: hidden; font-size: 1em; } .jsgrid input, .jsgrid textarea, .jsgrid select { font-size: 1em; } .jsgrid select { font-size: 1em; } .jsgrid-grid-header { overflow-x: hidden; overflow-y: scroll; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none; } .jsgrid-grid-body { overflow-x: auto; overflow-y: scroll; -webkit-overflow-scrolling: touch; } .jsgrid-table { width: 100%; table-layout: fixed; border-collapse: collapse; padding: 0.5em 0.5em; } .jsgrid-table td, .jsgrid-table th { box-sizing: border-box; } .jsgrid-header-cell { box-sizing: border-box; } .jsgrid-align-left { text-align: left; } .jsgrid-align-center, .jsgrid-align-center input, .jsgrid-align-center textarea, .jsgrid-align-center select { text-align: center; padding: .5em .5em; } .jsgrid-filter-row input, .jsgrid-filter-row textarea, .jsgrid-filter-row select, .jsgrid-edit-row input, .jsgrid-edit-row textarea, .jsgrid-edit-row select, .jsgrid-insert-row input, .jsgrid-insert-row textarea, .jsgrid-insert-row select { width: 90%; padding: .3em .5em; } .jsgrid-filter-row select, .jsgrid-edit-row input, .jsgrid-edit-row textarea, .jsgrid-edit-row select, .jsgrid-insert-row input, .jsgrid-insert-row textarea, .jsgrid-insert-row select { width: 100%; padding: .3em .5em; } .jsgrid-filter-row input[type='checkbox'], .jsgrid-edit-row input[type='checkbox'], .jsgrid-insert-row input[type='checkbox'] { width: auto; } .jsgrid-selected-row .jsgrid-cell { cursor: pointer; } .jsgrid-nodata-row .jsgrid-cell { padding: .5em 0; text-align: center; } .jsgrid-header-sort { cursor: pointer; } .jsgrid-pager { padding: .5em 0; } .jsgrid-pager-nav-button { padding: .2em .6em; } .jsgrid-pager-nav-inactive-button { display: none; pointer-events: none; } .jsgrid-pager-page { padding: .2em .6em; } <MSG> Theme: Css code formatting <DFF> @@ -4,7 +4,9 @@ font-size: 1em; } -.jsgrid input, .jsgrid textarea, .jsgrid select { +.jsgrid input, +.jsgrid textarea, +.jsgrid select { font-size: 1em; } @@ -36,7 +38,8 @@ padding: 0.5em 0.5em; } -.jsgrid-table td, .jsgrid-table th { +.jsgrid-table td, +.jsgrid-table th { box-sizing: border-box; } @@ -56,9 +59,15 @@ padding: .5em .5em; } -.jsgrid-filter-row input, .jsgrid-filter-row textarea, .jsgrid-filter-row select, -.jsgrid-edit-row input, .jsgrid-edit-row textarea, .jsgrid-edit-row select, -.jsgrid-insert-row input, .jsgrid-insert-row textarea, .jsgrid-insert-row select { +.jsgrid-filter-row input, +.jsgrid-filter-row textarea, +.jsgrid-filter-row select, +.jsgrid-edit-row input, +.jsgrid-edit-row textarea, +.jsgrid-edit-row select, +.jsgrid-insert-row input, +.jsgrid-insert-row textarea, +.jsgrid-insert-row select { width: 90%; padding: .3em .5em; }
14
Theme: Css code formatting
5
.css
css
mit
tabalinas/jsgrid
10062703
<NME> readme.hogan <BEF> # {{pkg.title}} [![Build Status](https://travis-ci.org/ftlabs/fruitmachine.svg?branch=master)](https://travis-ci.org/ftlabs/fruitmachine) [![Coverage Status](https://coveralls.io/repos/ftlabs/fruitmachine/badge.png?branch=master)](https://coveralls.io/r/ftlabs/fruitmachine?branch=master) [![Dependency Status](https://gemnasium.com/ftlabs/fruitmachine.png)](https://gemnasium.com/ftlabs/fruitmachine) {{pkg.description}} FruitMachine is designed to build rich interactive layouts from modular, reusable components. It's light and unopinionated so that it can be applied to almost any layout problem. FruitMachine is currently powering the [FT Web App](http://apps.ft.com/ftwebapp/). ```js // Define a module var Apple = fruitmachine.define({ name: 'apple', template: function(){ return 'hello' } }); // Create a module var apple = new Apple(); // Render it apple.render(); apple.el.outerHTML; //=> <div class="apple">hello</div> ``` ## Installation ``` $ npm install fruitmachine ``` or ``` $ bower install fruitmachine ``` or Download the [pre-built version][built] (~2k gzipped). [built]: http://wzrd.in/standalone/fruitmachine@latest ## Examples - [Article viewer](http://ftlabs.github.io/fruitmachine/examples/article-viewer/) - [TODO](http://ftlabs.github.io/fruitmachine/examples/todo/) ## Documentation - [Introduction](docs/introduction.md) - [Getting started](docs/getting-started.md) - [Defining modules](docs/defining-modules.md) - [Slots](docs/slots.md) - [View assembly](docs/layout-assembly.md) - [Instantiation](docs/module-instantiation.md) - [Templates](docs/templates.md) - [Template markup](docs/template-markup.md) - [Rendering](docs/rendering.md) - [DOM injection](docs/injection.md) - [The module element](docs/module-el.md) - [Queries](docs/queries.md) - [Helpers](docs/module-helpers.md) - [Removing & destroying](docs/removing-and-destroying.md) - [Removing & destroying](docs/removing-and-destroying.md) - [Extending](docs/extending-modules.md) - [Server-side rendering](docs/server-side-rendering.md) ## Tests ``` $ npm install $ npm test ``` #### Without PhantomJS ``` $ node_modules/.bin/buster-static ``` ...then visit http://localhost:8282/ in browser ## Author {{#pkg.author}} - **{{name}}** - [@{{github}}](http://github.com/{{github}}) {{/pkg.author}} ## Contributors {{#pkg.contributors}} - **{{name}}** - [@{{github}}](http://github.com/{{github}}) {{/pkg.contributors}} ## License Copyright (c) 2014 {{pkg.organization}} Licensed under the MIT license. ## Credits and collaboration The lead developer of {{pkg.title}} is [Wilson Page](http://github.com/wilsonpage) at FT Labs. All open source code released by FT Labs is licenced under the MIT licence. We welcome comments, feedback and suggestions. Please feel free to raise an issue or pull request. <MSG> Merge pull request #38 from matthew-andrews/update-docs Update docs <DFF> @@ -63,6 +63,8 @@ Download the [production version][min] (~2k gzipped) or the [development version - [Removing & destroying](docs/removing-and-destroying.md) - [Extending](docs/extending-modules.md) - [Server-side rendering](docs/server-side-rendering.md) +- [API](docs/api.md) +- [Events](docs/events.md) ## Tests
2
Merge pull request #38 from matthew-andrews/update-docs
0
.hogan
hogan
mit
ftlabs/fruitmachine
10062704
<NME> CollapsedLineSection.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics.CodeAnalysis; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a collapsed line section. /// Use the Uncollapse() method to uncollapse the section. /// </summary> public sealed class CollapsedLineSection { private readonly HeightTree _heightTree; #if DEBUG internal string Id; private static int _nextId; internal string Id; private static int _nextId; #else internal const string ID = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end) Start = start; End = end; #if DEBUG unchecked { Id = " #" + (_nextId++); } #endif } /// <summary> /// Gets if the document line is collapsed. /// This property initially is true and turns to false when uncollapsing the section. /// </summary> public bool IsCollapsed => Start != null; /// <summary> /// Gets the start line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine Start { get; internal set; } /// <summary> /// Gets the end line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine End { get; internal set; } /// <summary> /// Uncollapses the section. /// This causes the Start and End properties to be set to null! /// Does nothing if the section is already uncollapsed. /// </summary> public void Uncollapse() { if (Start == null) return; if (!_heightTree.IsDisposed) { _heightTree.Uncollapse(this); #if DEBUG _heightTree.CheckProperties(); #endif } Start = null; End = null; } /// <summary> /// Gets a string representation of the collapsed section. /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public override string ToString() { return "[CollapsedSection" + Id + " Start=" + (Start != null ? Start.LineNumber.ToString() : "null") + " End=" + (End != null ? End.LineNumber.ToString() : "null") + "]"; } } } <MSG> Merge remote-tracking branch 'origin/master' <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Rendering internal string Id; private static int _nextId; #else - internal const string ID = ""; + internal const string Id = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end)
1
Merge remote-tracking branch 'origin/master'
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062705
<NME> CollapsedLineSection.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics.CodeAnalysis; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a collapsed line section. /// Use the Uncollapse() method to uncollapse the section. /// </summary> public sealed class CollapsedLineSection { private readonly HeightTree _heightTree; #if DEBUG internal string Id; private static int _nextId; internal string Id; private static int _nextId; #else internal const string ID = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end) Start = start; End = end; #if DEBUG unchecked { Id = " #" + (_nextId++); } #endif } /// <summary> /// Gets if the document line is collapsed. /// This property initially is true and turns to false when uncollapsing the section. /// </summary> public bool IsCollapsed => Start != null; /// <summary> /// Gets the start line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine Start { get; internal set; } /// <summary> /// Gets the end line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine End { get; internal set; } /// <summary> /// Uncollapses the section. /// This causes the Start and End properties to be set to null! /// Does nothing if the section is already uncollapsed. /// </summary> public void Uncollapse() { if (Start == null) return; if (!_heightTree.IsDisposed) { _heightTree.Uncollapse(this); #if DEBUG _heightTree.CheckProperties(); #endif } Start = null; End = null; } /// <summary> /// Gets a string representation of the collapsed section. /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public override string ToString() { return "[CollapsedSection" + Id + " Start=" + (Start != null ? Start.LineNumber.ToString() : "null") + " End=" + (End != null ? End.LineNumber.ToString() : "null") + "]"; } } } <MSG> Merge remote-tracking branch 'origin/master' <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Rendering internal string Id; private static int _nextId; #else - internal const string ID = ""; + internal const string Id = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end)
1
Merge remote-tracking branch 'origin/master'
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062706
<NME> CollapsedLineSection.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics.CodeAnalysis; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a collapsed line section. /// Use the Uncollapse() method to uncollapse the section. /// </summary> public sealed class CollapsedLineSection { private readonly HeightTree _heightTree; #if DEBUG internal string Id; private static int _nextId; internal string Id; private static int _nextId; #else internal const string ID = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end) Start = start; End = end; #if DEBUG unchecked { Id = " #" + (_nextId++); } #endif } /// <summary> /// Gets if the document line is collapsed. /// This property initially is true and turns to false when uncollapsing the section. /// </summary> public bool IsCollapsed => Start != null; /// <summary> /// Gets the start line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine Start { get; internal set; } /// <summary> /// Gets the end line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine End { get; internal set; } /// <summary> /// Uncollapses the section. /// This causes the Start and End properties to be set to null! /// Does nothing if the section is already uncollapsed. /// </summary> public void Uncollapse() { if (Start == null) return; if (!_heightTree.IsDisposed) { _heightTree.Uncollapse(this); #if DEBUG _heightTree.CheckProperties(); #endif } Start = null; End = null; } /// <summary> /// Gets a string representation of the collapsed section. /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public override string ToString() { return "[CollapsedSection" + Id + " Start=" + (Start != null ? Start.LineNumber.ToString() : "null") + " End=" + (End != null ? End.LineNumber.ToString() : "null") + "]"; } } } <MSG> Merge remote-tracking branch 'origin/master' <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Rendering internal string Id; private static int _nextId; #else - internal const string ID = ""; + internal const string Id = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end)
1
Merge remote-tracking branch 'origin/master'
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062707
<NME> CollapsedLineSection.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics.CodeAnalysis; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a collapsed line section. /// Use the Uncollapse() method to uncollapse the section. /// </summary> public sealed class CollapsedLineSection { private readonly HeightTree _heightTree; #if DEBUG internal string Id; private static int _nextId; internal string Id; private static int _nextId; #else internal const string ID = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end) Start = start; End = end; #if DEBUG unchecked { Id = " #" + (_nextId++); } #endif } /// <summary> /// Gets if the document line is collapsed. /// This property initially is true and turns to false when uncollapsing the section. /// </summary> public bool IsCollapsed => Start != null; /// <summary> /// Gets the start line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine Start { get; internal set; } /// <summary> /// Gets the end line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine End { get; internal set; } /// <summary> /// Uncollapses the section. /// This causes the Start and End properties to be set to null! /// Does nothing if the section is already uncollapsed. /// </summary> public void Uncollapse() { if (Start == null) return; if (!_heightTree.IsDisposed) { _heightTree.Uncollapse(this); #if DEBUG _heightTree.CheckProperties(); #endif } Start = null; End = null; } /// <summary> /// Gets a string representation of the collapsed section. /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public override string ToString() { return "[CollapsedSection" + Id + " Start=" + (Start != null ? Start.LineNumber.ToString() : "null") + " End=" + (End != null ? End.LineNumber.ToString() : "null") + "]"; } } } <MSG> Merge remote-tracking branch 'origin/master' <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Rendering internal string Id; private static int _nextId; #else - internal const string ID = ""; + internal const string Id = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end)
1
Merge remote-tracking branch 'origin/master'
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062708
<NME> CollapsedLineSection.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics.CodeAnalysis; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a collapsed line section. /// Use the Uncollapse() method to uncollapse the section. /// </summary> public sealed class CollapsedLineSection { private readonly HeightTree _heightTree; #if DEBUG internal string Id; private static int _nextId; internal string Id; private static int _nextId; #else internal const string ID = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end) Start = start; End = end; #if DEBUG unchecked { Id = " #" + (_nextId++); } #endif } /// <summary> /// Gets if the document line is collapsed. /// This property initially is true and turns to false when uncollapsing the section. /// </summary> public bool IsCollapsed => Start != null; /// <summary> /// Gets the start line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine Start { get; internal set; } /// <summary> /// Gets the end line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine End { get; internal set; } /// <summary> /// Uncollapses the section. /// This causes the Start and End properties to be set to null! /// Does nothing if the section is already uncollapsed. /// </summary> public void Uncollapse() { if (Start == null) return; if (!_heightTree.IsDisposed) { _heightTree.Uncollapse(this); #if DEBUG _heightTree.CheckProperties(); #endif } Start = null; End = null; } /// <summary> /// Gets a string representation of the collapsed section. /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public override string ToString() { return "[CollapsedSection" + Id + " Start=" + (Start != null ? Start.LineNumber.ToString() : "null") + " End=" + (End != null ? End.LineNumber.ToString() : "null") + "]"; } } } <MSG> Merge remote-tracking branch 'origin/master' <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Rendering internal string Id; private static int _nextId; #else - internal const string ID = ""; + internal const string Id = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end)
1
Merge remote-tracking branch 'origin/master'
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062709
<NME> CollapsedLineSection.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics.CodeAnalysis; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a collapsed line section. /// Use the Uncollapse() method to uncollapse the section. /// </summary> public sealed class CollapsedLineSection { private readonly HeightTree _heightTree; #if DEBUG internal string Id; private static int _nextId; internal string Id; private static int _nextId; #else internal const string ID = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end) Start = start; End = end; #if DEBUG unchecked { Id = " #" + (_nextId++); } #endif } /// <summary> /// Gets if the document line is collapsed. /// This property initially is true and turns to false when uncollapsing the section. /// </summary> public bool IsCollapsed => Start != null; /// <summary> /// Gets the start line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine Start { get; internal set; } /// <summary> /// Gets the end line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine End { get; internal set; } /// <summary> /// Uncollapses the section. /// This causes the Start and End properties to be set to null! /// Does nothing if the section is already uncollapsed. /// </summary> public void Uncollapse() { if (Start == null) return; if (!_heightTree.IsDisposed) { _heightTree.Uncollapse(this); #if DEBUG _heightTree.CheckProperties(); #endif } Start = null; End = null; } /// <summary> /// Gets a string representation of the collapsed section. /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public override string ToString() { return "[CollapsedSection" + Id + " Start=" + (Start != null ? Start.LineNumber.ToString() : "null") + " End=" + (End != null ? End.LineNumber.ToString() : "null") + "]"; } } } <MSG> Merge remote-tracking branch 'origin/master' <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Rendering internal string Id; private static int _nextId; #else - internal const string ID = ""; + internal const string Id = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end)
1
Merge remote-tracking branch 'origin/master'
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062710
<NME> CollapsedLineSection.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics.CodeAnalysis; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a collapsed line section. /// Use the Uncollapse() method to uncollapse the section. /// </summary> public sealed class CollapsedLineSection { private readonly HeightTree _heightTree; #if DEBUG internal string Id; private static int _nextId; internal string Id; private static int _nextId; #else internal const string ID = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end) Start = start; End = end; #if DEBUG unchecked { Id = " #" + (_nextId++); } #endif } /// <summary> /// Gets if the document line is collapsed. /// This property initially is true and turns to false when uncollapsing the section. /// </summary> public bool IsCollapsed => Start != null; /// <summary> /// Gets the start line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine Start { get; internal set; } /// <summary> /// Gets the end line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine End { get; internal set; } /// <summary> /// Uncollapses the section. /// This causes the Start and End properties to be set to null! /// Does nothing if the section is already uncollapsed. /// </summary> public void Uncollapse() { if (Start == null) return; if (!_heightTree.IsDisposed) { _heightTree.Uncollapse(this); #if DEBUG _heightTree.CheckProperties(); #endif } Start = null; End = null; } /// <summary> /// Gets a string representation of the collapsed section. /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public override string ToString() { return "[CollapsedSection" + Id + " Start=" + (Start != null ? Start.LineNumber.ToString() : "null") + " End=" + (End != null ? End.LineNumber.ToString() : "null") + "]"; } } } <MSG> Merge remote-tracking branch 'origin/master' <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Rendering internal string Id; private static int _nextId; #else - internal const string ID = ""; + internal const string Id = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end)
1
Merge remote-tracking branch 'origin/master'
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062711
<NME> CollapsedLineSection.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics.CodeAnalysis; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a collapsed line section. /// Use the Uncollapse() method to uncollapse the section. /// </summary> public sealed class CollapsedLineSection { private readonly HeightTree _heightTree; #if DEBUG internal string Id; private static int _nextId; internal string Id; private static int _nextId; #else internal const string ID = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end) Start = start; End = end; #if DEBUG unchecked { Id = " #" + (_nextId++); } #endif } /// <summary> /// Gets if the document line is collapsed. /// This property initially is true and turns to false when uncollapsing the section. /// </summary> public bool IsCollapsed => Start != null; /// <summary> /// Gets the start line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine Start { get; internal set; } /// <summary> /// Gets the end line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine End { get; internal set; } /// <summary> /// Uncollapses the section. /// This causes the Start and End properties to be set to null! /// Does nothing if the section is already uncollapsed. /// </summary> public void Uncollapse() { if (Start == null) return; if (!_heightTree.IsDisposed) { _heightTree.Uncollapse(this); #if DEBUG _heightTree.CheckProperties(); #endif } Start = null; End = null; } /// <summary> /// Gets a string representation of the collapsed section. /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public override string ToString() { return "[CollapsedSection" + Id + " Start=" + (Start != null ? Start.LineNumber.ToString() : "null") + " End=" + (End != null ? End.LineNumber.ToString() : "null") + "]"; } } } <MSG> Merge remote-tracking branch 'origin/master' <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Rendering internal string Id; private static int _nextId; #else - internal const string ID = ""; + internal const string Id = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end)
1
Merge remote-tracking branch 'origin/master'
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062712
<NME> CollapsedLineSection.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics.CodeAnalysis; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a collapsed line section. /// Use the Uncollapse() method to uncollapse the section. /// </summary> public sealed class CollapsedLineSection { private readonly HeightTree _heightTree; #if DEBUG internal string Id; private static int _nextId; internal string Id; private static int _nextId; #else internal const string ID = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end) Start = start; End = end; #if DEBUG unchecked { Id = " #" + (_nextId++); } #endif } /// <summary> /// Gets if the document line is collapsed. /// This property initially is true and turns to false when uncollapsing the section. /// </summary> public bool IsCollapsed => Start != null; /// <summary> /// Gets the start line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine Start { get; internal set; } /// <summary> /// Gets the end line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine End { get; internal set; } /// <summary> /// Uncollapses the section. /// This causes the Start and End properties to be set to null! /// Does nothing if the section is already uncollapsed. /// </summary> public void Uncollapse() { if (Start == null) return; if (!_heightTree.IsDisposed) { _heightTree.Uncollapse(this); #if DEBUG _heightTree.CheckProperties(); #endif } Start = null; End = null; } /// <summary> /// Gets a string representation of the collapsed section. /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public override string ToString() { return "[CollapsedSection" + Id + " Start=" + (Start != null ? Start.LineNumber.ToString() : "null") + " End=" + (End != null ? End.LineNumber.ToString() : "null") + "]"; } } } <MSG> Merge remote-tracking branch 'origin/master' <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Rendering internal string Id; private static int _nextId; #else - internal const string ID = ""; + internal const string Id = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end)
1
Merge remote-tracking branch 'origin/master'
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062713
<NME> CollapsedLineSection.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics.CodeAnalysis; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a collapsed line section. /// Use the Uncollapse() method to uncollapse the section. /// </summary> public sealed class CollapsedLineSection { private readonly HeightTree _heightTree; #if DEBUG internal string Id; private static int _nextId; internal string Id; private static int _nextId; #else internal const string ID = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end) Start = start; End = end; #if DEBUG unchecked { Id = " #" + (_nextId++); } #endif } /// <summary> /// Gets if the document line is collapsed. /// This property initially is true and turns to false when uncollapsing the section. /// </summary> public bool IsCollapsed => Start != null; /// <summary> /// Gets the start line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine Start { get; internal set; } /// <summary> /// Gets the end line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine End { get; internal set; } /// <summary> /// Uncollapses the section. /// This causes the Start and End properties to be set to null! /// Does nothing if the section is already uncollapsed. /// </summary> public void Uncollapse() { if (Start == null) return; if (!_heightTree.IsDisposed) { _heightTree.Uncollapse(this); #if DEBUG _heightTree.CheckProperties(); #endif } Start = null; End = null; } /// <summary> /// Gets a string representation of the collapsed section. /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public override string ToString() { return "[CollapsedSection" + Id + " Start=" + (Start != null ? Start.LineNumber.ToString() : "null") + " End=" + (End != null ? End.LineNumber.ToString() : "null") + "]"; } } } <MSG> Merge remote-tracking branch 'origin/master' <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Rendering internal string Id; private static int _nextId; #else - internal const string ID = ""; + internal const string Id = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end)
1
Merge remote-tracking branch 'origin/master'
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062714
<NME> CollapsedLineSection.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics.CodeAnalysis; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a collapsed line section. /// Use the Uncollapse() method to uncollapse the section. /// </summary> public sealed class CollapsedLineSection { private readonly HeightTree _heightTree; #if DEBUG internal string Id; private static int _nextId; internal string Id; private static int _nextId; #else internal const string ID = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end) Start = start; End = end; #if DEBUG unchecked { Id = " #" + (_nextId++); } #endif } /// <summary> /// Gets if the document line is collapsed. /// This property initially is true and turns to false when uncollapsing the section. /// </summary> public bool IsCollapsed => Start != null; /// <summary> /// Gets the start line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine Start { get; internal set; } /// <summary> /// Gets the end line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine End { get; internal set; } /// <summary> /// Uncollapses the section. /// This causes the Start and End properties to be set to null! /// Does nothing if the section is already uncollapsed. /// </summary> public void Uncollapse() { if (Start == null) return; if (!_heightTree.IsDisposed) { _heightTree.Uncollapse(this); #if DEBUG _heightTree.CheckProperties(); #endif } Start = null; End = null; } /// <summary> /// Gets a string representation of the collapsed section. /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public override string ToString() { return "[CollapsedSection" + Id + " Start=" + (Start != null ? Start.LineNumber.ToString() : "null") + " End=" + (End != null ? End.LineNumber.ToString() : "null") + "]"; } } } <MSG> Merge remote-tracking branch 'origin/master' <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Rendering internal string Id; private static int _nextId; #else - internal const string ID = ""; + internal const string Id = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end)
1
Merge remote-tracking branch 'origin/master'
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062715
<NME> CollapsedLineSection.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics.CodeAnalysis; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a collapsed line section. /// Use the Uncollapse() method to uncollapse the section. /// </summary> public sealed class CollapsedLineSection { private readonly HeightTree _heightTree; #if DEBUG internal string Id; private static int _nextId; internal string Id; private static int _nextId; #else internal const string ID = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end) Start = start; End = end; #if DEBUG unchecked { Id = " #" + (_nextId++); } #endif } /// <summary> /// Gets if the document line is collapsed. /// This property initially is true and turns to false when uncollapsing the section. /// </summary> public bool IsCollapsed => Start != null; /// <summary> /// Gets the start line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine Start { get; internal set; } /// <summary> /// Gets the end line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine End { get; internal set; } /// <summary> /// Uncollapses the section. /// This causes the Start and End properties to be set to null! /// Does nothing if the section is already uncollapsed. /// </summary> public void Uncollapse() { if (Start == null) return; if (!_heightTree.IsDisposed) { _heightTree.Uncollapse(this); #if DEBUG _heightTree.CheckProperties(); #endif } Start = null; End = null; } /// <summary> /// Gets a string representation of the collapsed section. /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public override string ToString() { return "[CollapsedSection" + Id + " Start=" + (Start != null ? Start.LineNumber.ToString() : "null") + " End=" + (End != null ? End.LineNumber.ToString() : "null") + "]"; } } } <MSG> Merge remote-tracking branch 'origin/master' <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Rendering internal string Id; private static int _nextId; #else - internal const string ID = ""; + internal const string Id = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end)
1
Merge remote-tracking branch 'origin/master'
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062716
<NME> CollapsedLineSection.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics.CodeAnalysis; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a collapsed line section. /// Use the Uncollapse() method to uncollapse the section. /// </summary> public sealed class CollapsedLineSection { private readonly HeightTree _heightTree; #if DEBUG internal string Id; private static int _nextId; internal string Id; private static int _nextId; #else internal const string ID = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end) Start = start; End = end; #if DEBUG unchecked { Id = " #" + (_nextId++); } #endif } /// <summary> /// Gets if the document line is collapsed. /// This property initially is true and turns to false when uncollapsing the section. /// </summary> public bool IsCollapsed => Start != null; /// <summary> /// Gets the start line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine Start { get; internal set; } /// <summary> /// Gets the end line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine End { get; internal set; } /// <summary> /// Uncollapses the section. /// This causes the Start and End properties to be set to null! /// Does nothing if the section is already uncollapsed. /// </summary> public void Uncollapse() { if (Start == null) return; if (!_heightTree.IsDisposed) { _heightTree.Uncollapse(this); #if DEBUG _heightTree.CheckProperties(); #endif } Start = null; End = null; } /// <summary> /// Gets a string representation of the collapsed section. /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public override string ToString() { return "[CollapsedSection" + Id + " Start=" + (Start != null ? Start.LineNumber.ToString() : "null") + " End=" + (End != null ? End.LineNumber.ToString() : "null") + "]"; } } } <MSG> Merge remote-tracking branch 'origin/master' <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Rendering internal string Id; private static int _nextId; #else - internal const string ID = ""; + internal const string Id = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end)
1
Merge remote-tracking branch 'origin/master'
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062717
<NME> CollapsedLineSection.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics.CodeAnalysis; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a collapsed line section. /// Use the Uncollapse() method to uncollapse the section. /// </summary> public sealed class CollapsedLineSection { private readonly HeightTree _heightTree; #if DEBUG internal string Id; private static int _nextId; internal string Id; private static int _nextId; #else internal const string ID = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end) Start = start; End = end; #if DEBUG unchecked { Id = " #" + (_nextId++); } #endif } /// <summary> /// Gets if the document line is collapsed. /// This property initially is true and turns to false when uncollapsing the section. /// </summary> public bool IsCollapsed => Start != null; /// <summary> /// Gets the start line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine Start { get; internal set; } /// <summary> /// Gets the end line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine End { get; internal set; } /// <summary> /// Uncollapses the section. /// This causes the Start and End properties to be set to null! /// Does nothing if the section is already uncollapsed. /// </summary> public void Uncollapse() { if (Start == null) return; if (!_heightTree.IsDisposed) { _heightTree.Uncollapse(this); #if DEBUG _heightTree.CheckProperties(); #endif } Start = null; End = null; } /// <summary> /// Gets a string representation of the collapsed section. /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public override string ToString() { return "[CollapsedSection" + Id + " Start=" + (Start != null ? Start.LineNumber.ToString() : "null") + " End=" + (End != null ? End.LineNumber.ToString() : "null") + "]"; } } } <MSG> Merge remote-tracking branch 'origin/master' <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Rendering internal string Id; private static int _nextId; #else - internal const string ID = ""; + internal const string Id = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end)
1
Merge remote-tracking branch 'origin/master'
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062718
<NME> CollapsedLineSection.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 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.Diagnostics.CodeAnalysis; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Represents a collapsed line section. /// Use the Uncollapse() method to uncollapse the section. /// </summary> public sealed class CollapsedLineSection { private readonly HeightTree _heightTree; #if DEBUG internal string Id; private static int _nextId; internal string Id; private static int _nextId; #else internal const string ID = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end) Start = start; End = end; #if DEBUG unchecked { Id = " #" + (_nextId++); } #endif } /// <summary> /// Gets if the document line is collapsed. /// This property initially is true and turns to false when uncollapsing the section. /// </summary> public bool IsCollapsed => Start != null; /// <summary> /// Gets the start line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine Start { get; internal set; } /// <summary> /// Gets the end line of the section. /// When the section is uncollapsed or the text containing it is deleted, /// this property returns null. /// </summary> public DocumentLine End { get; internal set; } /// <summary> /// Uncollapses the section. /// This causes the Start and End properties to be set to null! /// Does nothing if the section is already uncollapsed. /// </summary> public void Uncollapse() { if (Start == null) return; if (!_heightTree.IsDisposed) { _heightTree.Uncollapse(this); #if DEBUG _heightTree.CheckProperties(); #endif } Start = null; End = null; } /// <summary> /// Gets a string representation of the collapsed section. /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public override string ToString() { return "[CollapsedSection" + Id + " Start=" + (Start != null ? Start.LineNumber.ToString() : "null") + " End=" + (End != null ? End.LineNumber.ToString() : "null") + "]"; } } } <MSG> Merge remote-tracking branch 'origin/master' <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.Rendering internal string Id; private static int _nextId; #else - internal const string ID = ""; + internal const string Id = ""; #endif internal CollapsedLineSection(HeightTree heightTree, DocumentLine start, DocumentLine end)
1
Merge remote-tracking branch 'origin/master'
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062719
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. * Line numeration. * Display whitespaces EOLs and tabs. * Line virtualization. * Multi-caret edition. * Intra-column adornments. * Word wrapping. * Scrolling below document. * Hyperlinks. and many,many more! AvaloniaEdit currently consists of 2 packages * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. ### How to set up TextMate theme and syntax highlighting for my project? First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages: //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` //Here we initialize RegistryOptions with the theme we want to use. var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> more fixes <DFF> @@ -30,7 +30,7 @@ var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); -//Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ```
1
more fixes
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10062720
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. * Line numeration. * Display whitespaces EOLs and tabs. * Line virtualization. * Multi-caret edition. * Intra-column adornments. * Word wrapping. * Scrolling below document. * Hyperlinks. and many,many more! AvaloniaEdit currently consists of 2 packages * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. ### How to set up TextMate theme and syntax highlighting for my project? First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages: //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` //Here we initialize RegistryOptions with the theme we want to use. var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> more fixes <DFF> @@ -30,7 +30,7 @@ var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); -//Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ```
1
more fixes
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10062721
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. * Line numeration. * Display whitespaces EOLs and tabs. * Line virtualization. * Multi-caret edition. * Intra-column adornments. * Word wrapping. * Scrolling below document. * Hyperlinks. and many,many more! AvaloniaEdit currently consists of 2 packages * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. ### How to set up TextMate theme and syntax highlighting for my project? First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages: //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` //Here we initialize RegistryOptions with the theme we want to use. var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> more fixes <DFF> @@ -30,7 +30,7 @@ var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); -//Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ```
1
more fixes
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10062722
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. * Line numeration. * Display whitespaces EOLs and tabs. * Line virtualization. * Multi-caret edition. * Intra-column adornments. * Word wrapping. * Scrolling below document. * Hyperlinks. and many,many more! AvaloniaEdit currently consists of 2 packages * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. ### How to set up TextMate theme and syntax highlighting for my project? First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages: //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` //Here we initialize RegistryOptions with the theme we want to use. var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> more fixes <DFF> @@ -30,7 +30,7 @@ var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); -//Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ```
1
more fixes
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10062723
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. * Line numeration. * Display whitespaces EOLs and tabs. * Line virtualization. * Multi-caret edition. * Intra-column adornments. * Word wrapping. * Scrolling below document. * Hyperlinks. and many,many more! AvaloniaEdit currently consists of 2 packages * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. ### How to set up TextMate theme and syntax highlighting for my project? First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages: //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` //Here we initialize RegistryOptions with the theme we want to use. var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> more fixes <DFF> @@ -30,7 +30,7 @@ var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); -//Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ```
1
more fixes
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10062724
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. * Line numeration. * Display whitespaces EOLs and tabs. * Line virtualization. * Multi-caret edition. * Intra-column adornments. * Word wrapping. * Scrolling below document. * Hyperlinks. and many,many more! AvaloniaEdit currently consists of 2 packages * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. ### How to set up TextMate theme and syntax highlighting for my project? First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages: //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` //Here we initialize RegistryOptions with the theme we want to use. var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> more fixes <DFF> @@ -30,7 +30,7 @@ var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); -//Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ```
1
more fixes
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10062725
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. * Line numeration. * Display whitespaces EOLs and tabs. * Line virtualization. * Multi-caret edition. * Intra-column adornments. * Word wrapping. * Scrolling below document. * Hyperlinks. and many,many more! AvaloniaEdit currently consists of 2 packages * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. ### How to set up TextMate theme and syntax highlighting for my project? First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages: //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` //Here we initialize RegistryOptions with the theme we want to use. var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> more fixes <DFF> @@ -30,7 +30,7 @@ var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); -//Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ```
1
more fixes
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10062726
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. * Line numeration. * Display whitespaces EOLs and tabs. * Line virtualization. * Multi-caret edition. * Intra-column adornments. * Word wrapping. * Scrolling below document. * Hyperlinks. and many,many more! AvaloniaEdit currently consists of 2 packages * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. ### How to set up TextMate theme and syntax highlighting for my project? First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages: //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` //Here we initialize RegistryOptions with the theme we want to use. var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> more fixes <DFF> @@ -30,7 +30,7 @@ var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); -//Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ```
1
more fixes
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10062727
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. * Line numeration. * Display whitespaces EOLs and tabs. * Line virtualization. * Multi-caret edition. * Intra-column adornments. * Word wrapping. * Scrolling below document. * Hyperlinks. and many,many more! AvaloniaEdit currently consists of 2 packages * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. ### How to set up TextMate theme and syntax highlighting for my project? First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages: //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` //Here we initialize RegistryOptions with the theme we want to use. var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> more fixes <DFF> @@ -30,7 +30,7 @@ var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); -//Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ```
1
more fixes
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10062728
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. * Line numeration. * Display whitespaces EOLs and tabs. * Line virtualization. * Multi-caret edition. * Intra-column adornments. * Word wrapping. * Scrolling below document. * Hyperlinks. and many,many more! AvaloniaEdit currently consists of 2 packages * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. ### How to set up TextMate theme and syntax highlighting for my project? First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages: //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` //Here we initialize RegistryOptions with the theme we want to use. var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> more fixes <DFF> @@ -30,7 +30,7 @@ var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); -//Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ```
1
more fixes
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10062729
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. * Line numeration. * Display whitespaces EOLs and tabs. * Line virtualization. * Multi-caret edition. * Intra-column adornments. * Word wrapping. * Scrolling below document. * Hyperlinks. and many,many more! AvaloniaEdit currently consists of 2 packages * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. ### How to set up TextMate theme and syntax highlighting for my project? First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages: //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` //Here we initialize RegistryOptions with the theme we want to use. var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> more fixes <DFF> @@ -30,7 +30,7 @@ var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); -//Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ```
1
more fixes
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10062730
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. * Line numeration. * Display whitespaces EOLs and tabs. * Line virtualization. * Multi-caret edition. * Intra-column adornments. * Word wrapping. * Scrolling below document. * Hyperlinks. and many,many more! AvaloniaEdit currently consists of 2 packages * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. ### How to set up TextMate theme and syntax highlighting for my project? First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages: //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` //Here we initialize RegistryOptions with the theme we want to use. var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> more fixes <DFF> @@ -30,7 +30,7 @@ var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); -//Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ```
1
more fixes
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10062731
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. * Line numeration. * Display whitespaces EOLs and tabs. * Line virtualization. * Multi-caret edition. * Intra-column adornments. * Word wrapping. * Scrolling below document. * Hyperlinks. and many,many more! AvaloniaEdit currently consists of 2 packages * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. ### How to set up TextMate theme and syntax highlighting for my project? First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages: //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` //Here we initialize RegistryOptions with the theme we want to use. var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> more fixes <DFF> @@ -30,7 +30,7 @@ var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); -//Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ```
1
more fixes
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10062732
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. * Line numeration. * Display whitespaces EOLs and tabs. * Line virtualization. * Multi-caret edition. * Intra-column adornments. * Word wrapping. * Scrolling below document. * Hyperlinks. and many,many more! AvaloniaEdit currently consists of 2 packages * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. ### How to set up TextMate theme and syntax highlighting for my project? First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages: //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` //Here we initialize RegistryOptions with the theme we want to use. var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> more fixes <DFF> @@ -30,7 +30,7 @@ var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); -//Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ```
1
more fixes
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10062733
<NME> README.md <BEF> [![downloads](https://img.shields.io/nuget/dt/avalonia.AvaloniaEdit)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) [![Current stable version](https://img.shields.io/nuget/v/Avalonia.AvaloniaEdit.svg)](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) # AvaloniaEdit This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit), a WPF-based text editor for [Avalonia](https://github.com/AvaloniaUI/Avalonia). AvaloniaEdit supports features like: * Syntax highlighting using [TextMate](https://github.com/danipen/TextMateSharp) grammars and themes. * Code folding. * Code completion. * Fully customizable and extensible. * Line numeration. * Display whitespaces EOLs and tabs. * Line virtualization. * Multi-caret edition. * Intra-column adornments. * Word wrapping. * Scrolling below document. * Hyperlinks. and many,many more! AvaloniaEdit currently consists of 2 packages * [Avalonia.AvaloniaEdit](https://www.nuget.org/packages/Avalonia.AvaloniaEdit) well-known package that incudes text editor itself. * [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) package that adds TextMate integration to the AvaloniaEdit. ### How to set up TextMate theme and syntax highlighting for my project? First of all, if you want to use grammars supported by [TextMateSharp](https://github.com/danipen/TextMateSharp), should install the following packages: //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` //Here we initialize RegistryOptions with the theme we want to use. var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); //Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ``` ![avaloniaedit-demo](https://user-images.githubusercontent.com/501613/169226248-946e716d-dea3-4c6d-9ae9-6148b2a51f03.gif) <MSG> more fixes <DFF> @@ -30,7 +30,7 @@ var _registryOptions = new RegistryOptions(ThemeName.DarkPlus); //Initial setup of TextMate. var _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); -//Here we are getting the lanuage by the extension and right after that we are initializing grammar with this lanuage. +//Here we are getting the language by the extension and right after that we are initializing grammar with this language. //And that's all 😀, you are ready to use AvaloniaEdit with syntax highlighting! _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(_registryOptions.GetLanguageByExtension(".cs").Id)); ```
1
more fixes
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10062734
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; if (e.InsertionLength > 0) { int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); if (startLine == 0) { InvalidateLine(startLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) { SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Merge pull request #222 from AvaloniaUI/fix-221 Fix syntax highlighting is not applied sometimes <DFF> @@ -109,10 +109,10 @@ namespace AvaloniaEdit.TextMate try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; - + int endLine = startLine; if (e.InsertionLength > 0) { - int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; + endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { @@ -124,13 +124,14 @@ namespace AvaloniaEdit.TextMate if (startLine == 0) { - InvalidateLine(startLine); + InvalidateLineRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too - InvalidateLineRange(startLine - 1, startLine); + + InvalidateLineRange(startLine - 1, endLine); } catch (Exception ex) {
5
Merge pull request #222 from AvaloniaUI/fix-221
4
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10062735
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; if (e.InsertionLength > 0) { int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); if (startLine == 0) { InvalidateLine(startLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) { SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Merge pull request #222 from AvaloniaUI/fix-221 Fix syntax highlighting is not applied sometimes <DFF> @@ -109,10 +109,10 @@ namespace AvaloniaEdit.TextMate try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; - + int endLine = startLine; if (e.InsertionLength > 0) { - int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; + endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { @@ -124,13 +124,14 @@ namespace AvaloniaEdit.TextMate if (startLine == 0) { - InvalidateLine(startLine); + InvalidateLineRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too - InvalidateLineRange(startLine - 1, startLine); + + InvalidateLineRange(startLine - 1, endLine); } catch (Exception ex) {
5
Merge pull request #222 from AvaloniaUI/fix-221
4
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10062736
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; if (e.InsertionLength > 0) { int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); if (startLine == 0) { InvalidateLine(startLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) { SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Merge pull request #222 from AvaloniaUI/fix-221 Fix syntax highlighting is not applied sometimes <DFF> @@ -109,10 +109,10 @@ namespace AvaloniaEdit.TextMate try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; - + int endLine = startLine; if (e.InsertionLength > 0) { - int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; + endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { @@ -124,13 +124,14 @@ namespace AvaloniaEdit.TextMate if (startLine == 0) { - InvalidateLine(startLine); + InvalidateLineRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too - InvalidateLineRange(startLine - 1, startLine); + + InvalidateLineRange(startLine - 1, endLine); } catch (Exception ex) {
5
Merge pull request #222 from AvaloniaUI/fix-221
4
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10062737
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; if (e.InsertionLength > 0) { int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); if (startLine == 0) { InvalidateLine(startLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) { SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Merge pull request #222 from AvaloniaUI/fix-221 Fix syntax highlighting is not applied sometimes <DFF> @@ -109,10 +109,10 @@ namespace AvaloniaEdit.TextMate try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; - + int endLine = startLine; if (e.InsertionLength > 0) { - int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; + endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { @@ -124,13 +124,14 @@ namespace AvaloniaEdit.TextMate if (startLine == 0) { - InvalidateLine(startLine); + InvalidateLineRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too - InvalidateLineRange(startLine - 1, startLine); + + InvalidateLineRange(startLine - 1, endLine); } catch (Exception ex) {
5
Merge pull request #222 from AvaloniaUI/fix-221
4
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10062738
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; if (e.InsertionLength > 0) { int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); if (startLine == 0) { InvalidateLine(startLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) { SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Merge pull request #222 from AvaloniaUI/fix-221 Fix syntax highlighting is not applied sometimes <DFF> @@ -109,10 +109,10 @@ namespace AvaloniaEdit.TextMate try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; - + int endLine = startLine; if (e.InsertionLength > 0) { - int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; + endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { @@ -124,13 +124,14 @@ namespace AvaloniaEdit.TextMate if (startLine == 0) { - InvalidateLine(startLine); + InvalidateLineRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too - InvalidateLineRange(startLine - 1, startLine); + + InvalidateLineRange(startLine - 1, endLine); } catch (Exception ex) {
5
Merge pull request #222 from AvaloniaUI/fix-221
4
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10062739
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; if (e.InsertionLength > 0) { int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); if (startLine == 0) { InvalidateLine(startLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) { SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Merge pull request #222 from AvaloniaUI/fix-221 Fix syntax highlighting is not applied sometimes <DFF> @@ -109,10 +109,10 @@ namespace AvaloniaEdit.TextMate try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; - + int endLine = startLine; if (e.InsertionLength > 0) { - int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; + endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { @@ -124,13 +124,14 @@ namespace AvaloniaEdit.TextMate if (startLine == 0) { - InvalidateLine(startLine); + InvalidateLineRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too - InvalidateLineRange(startLine - 1, startLine); + + InvalidateLineRange(startLine - 1, endLine); } catch (Exception ex) {
5
Merge pull request #222 from AvaloniaUI/fix-221
4
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10062740
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; if (e.InsertionLength > 0) { int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); if (startLine == 0) { InvalidateLine(startLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) { SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Merge pull request #222 from AvaloniaUI/fix-221 Fix syntax highlighting is not applied sometimes <DFF> @@ -109,10 +109,10 @@ namespace AvaloniaEdit.TextMate try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; - + int endLine = startLine; if (e.InsertionLength > 0) { - int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; + endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { @@ -124,13 +124,14 @@ namespace AvaloniaEdit.TextMate if (startLine == 0) { - InvalidateLine(startLine); + InvalidateLineRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too - InvalidateLineRange(startLine - 1, startLine); + + InvalidateLineRange(startLine - 1, endLine); } catch (Exception ex) {
5
Merge pull request #222 from AvaloniaUI/fix-221
4
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10062741
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; if (e.InsertionLength > 0) { int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); if (startLine == 0) { InvalidateLine(startLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) { SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Merge pull request #222 from AvaloniaUI/fix-221 Fix syntax highlighting is not applied sometimes <DFF> @@ -109,10 +109,10 @@ namespace AvaloniaEdit.TextMate try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; - + int endLine = startLine; if (e.InsertionLength > 0) { - int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; + endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { @@ -124,13 +124,14 @@ namespace AvaloniaEdit.TextMate if (startLine == 0) { - InvalidateLine(startLine); + InvalidateLineRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too - InvalidateLineRange(startLine - 1, startLine); + + InvalidateLineRange(startLine - 1, endLine); } catch (Exception ex) {
5
Merge pull request #222 from AvaloniaUI/fix-221
4
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10062742
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; if (e.InsertionLength > 0) { int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); if (startLine == 0) { InvalidateLine(startLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) { SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Merge pull request #222 from AvaloniaUI/fix-221 Fix syntax highlighting is not applied sometimes <DFF> @@ -109,10 +109,10 @@ namespace AvaloniaEdit.TextMate try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; - + int endLine = startLine; if (e.InsertionLength > 0) { - int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; + endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { @@ -124,13 +124,14 @@ namespace AvaloniaEdit.TextMate if (startLine == 0) { - InvalidateLine(startLine); + InvalidateLineRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too - InvalidateLineRange(startLine - 1, startLine); + + InvalidateLineRange(startLine - 1, endLine); } catch (Exception ex) {
5
Merge pull request #222 from AvaloniaUI/fix-221
4
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10062743
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; if (e.InsertionLength > 0) { int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); if (startLine == 0) { InvalidateLine(startLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) { SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Merge pull request #222 from AvaloniaUI/fix-221 Fix syntax highlighting is not applied sometimes <DFF> @@ -109,10 +109,10 @@ namespace AvaloniaEdit.TextMate try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; - + int endLine = startLine; if (e.InsertionLength > 0) { - int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; + endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { @@ -124,13 +124,14 @@ namespace AvaloniaEdit.TextMate if (startLine == 0) { - InvalidateLine(startLine); + InvalidateLineRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too - InvalidateLineRange(startLine - 1, startLine); + + InvalidateLineRange(startLine - 1, endLine); } catch (Exception ex) {
5
Merge pull request #222 from AvaloniaUI/fix-221
4
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10062744
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; if (e.InsertionLength > 0) { int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); if (startLine == 0) { InvalidateLine(startLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) { SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Merge pull request #222 from AvaloniaUI/fix-221 Fix syntax highlighting is not applied sometimes <DFF> @@ -109,10 +109,10 @@ namespace AvaloniaEdit.TextMate try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; - + int endLine = startLine; if (e.InsertionLength > 0) { - int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; + endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { @@ -124,13 +124,14 @@ namespace AvaloniaEdit.TextMate if (startLine == 0) { - InvalidateLine(startLine); + InvalidateLineRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too - InvalidateLineRange(startLine - 1, startLine); + + InvalidateLineRange(startLine - 1, endLine); } catch (Exception ex) {
5
Merge pull request #222 from AvaloniaUI/fix-221
4
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10062745
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; if (e.InsertionLength > 0) { int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); if (startLine == 0) { InvalidateLine(startLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) { SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Merge pull request #222 from AvaloniaUI/fix-221 Fix syntax highlighting is not applied sometimes <DFF> @@ -109,10 +109,10 @@ namespace AvaloniaEdit.TextMate try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; - + int endLine = startLine; if (e.InsertionLength > 0) { - int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; + endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { @@ -124,13 +124,14 @@ namespace AvaloniaEdit.TextMate if (startLine == 0) { - InvalidateLine(startLine); + InvalidateLineRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too - InvalidateLineRange(startLine - 1, startLine); + + InvalidateLineRange(startLine - 1, endLine); } catch (Exception ex) {
5
Merge pull request #222 from AvaloniaUI/fix-221
4
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10062746
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; if (e.InsertionLength > 0) { int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); if (startLine == 0) { InvalidateLine(startLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) { SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Merge pull request #222 from AvaloniaUI/fix-221 Fix syntax highlighting is not applied sometimes <DFF> @@ -109,10 +109,10 @@ namespace AvaloniaEdit.TextMate try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; - + int endLine = startLine; if (e.InsertionLength > 0) { - int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; + endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { @@ -124,13 +124,14 @@ namespace AvaloniaEdit.TextMate if (startLine == 0) { - InvalidateLine(startLine); + InvalidateLineRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too - InvalidateLineRange(startLine - 1, startLine); + + InvalidateLineRange(startLine - 1, endLine); } catch (Exception ex) {
5
Merge pull request #222 from AvaloniaUI/fix-221
4
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10062747
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; if (e.InsertionLength > 0) { int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); if (startLine == 0) { InvalidateLine(startLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) { SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Merge pull request #222 from AvaloniaUI/fix-221 Fix syntax highlighting is not applied sometimes <DFF> @@ -109,10 +109,10 @@ namespace AvaloniaEdit.TextMate try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; - + int endLine = startLine; if (e.InsertionLength > 0) { - int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; + endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { @@ -124,13 +124,14 @@ namespace AvaloniaEdit.TextMate if (startLine == 0) { - InvalidateLine(startLine); + InvalidateLineRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too - InvalidateLineRange(startLine - 1, startLine); + + InvalidateLineRange(startLine - 1, endLine); } catch (Exception ex) {
5
Merge pull request #222 from AvaloniaUI/fix-221
4
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10062748
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; if (e.InsertionLength > 0) { int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); if (startLine == 0) { InvalidateLine(startLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) { SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Merge pull request #222 from AvaloniaUI/fix-221 Fix syntax highlighting is not applied sometimes <DFF> @@ -109,10 +109,10 @@ namespace AvaloniaEdit.TextMate try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; - + int endLine = startLine; if (e.InsertionLength > 0) { - int endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; + endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { @@ -124,13 +124,14 @@ namespace AvaloniaEdit.TextMate if (startLine == 0) { - InvalidateLine(startLine); + InvalidateLineRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too - InvalidateLineRange(startLine - 1, startLine); + + InvalidateLineRange(startLine - 1, endLine); } catch (Exception ex) {
5
Merge pull request #222 from AvaloniaUI/fix-221
4
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10062749
<NME> index.js <BEF> /*jshint browser:true, node:true*/ 'use strict'; /** * Module Dependencies */ var util = require('utils'); var events = require('./events'); var extend = require('extend'); var mixin = util.mixin; /** * Exports */ module.exports = function(fm) { // Alias prototype for optimum // compression via uglifyjs var proto = Module.prototype; /** * Module constructor * * Options: * * - `id {String}` a unique id to query by * - `model {Object|Model}` the data with which to associate this module * - `tag {String}` tagName to use for the root element * - `classes {Array}` list of classes to add to the root element * - `template {Function}` a template to use for rendering * - `helpers {Array}`a list of helper function to use on this module * - `children {Object|Array}` list of child modules * * @constructor * @param {Object} options * @api public */ function Module(options) { // Shallow clone the options options = mixin({}, options); // Various config steps this._configure(options); this._add(options.children); // Fire before initialize event hook this.fireStatic('before initialize', options); // Run initialize hooks if (this.initialize) this.initialize(options); // Fire initialize event hook this.fireStatic('initialize', options); } /** * Configures the new Module * with the options passed * to the constructor. * * @param {Object} options * @api private */ proto._configure = function(options) { // Setup static properties this._id = options.id || util.uniqueId(); this._fmid = options.fmid || util.uniqueId('fmid'); this.tag = options.tag || this.tag || 'div'; this.classes = options.classes || this.classes || []; this.helpers = options.helpers || this.helpers || []; this.template = this._setTemplate(options.template || this.template); this.slot = options.slot; // Create id and module // lookup objects this.children = []; this._ids = {}; this._modules = {}; this.slots = {}; // Use the model passed in, // or create a model from // the data passed in. var model = options.model || options.data || {}; this.model = util.isPlainObject(model) ? new this.Model(model) : model; // Attach helpers // TODO: Fix this for non-ES5 environments this.helpers.forEach(this.attachHelper, this); // We fire and 'inflation' event here // so that helpers can make some changes // to the view before instantiation. if (options.fmid) { fm.fire('inflation', this, options); this.fireStatic('inflation', options); } }; /** * A private add method * that accepts a list of * children. * * @param {Object|Array} children * @api private */ proto._add = function(children) { if (!children) return; var isArray = util.isArray(children); var child; for (var key in children) { child = children[key]; if (!isArray) child.slot = key; this.add(child); } }, /** * Instantiates the given * helper on the Module. * * @param {Function} helper * @return {Module} * @api private */ proto.attachHelper = function(helper) { if (helper) helper(this); }, /** * Returns the template function * for the view. * * For template object like Hogan * templates with a `render` method * we need to bind the context * so they can be called without * a reciever. * * @return {Function} * @api private */ proto._setTemplate = function(fn) { return fn && fn.render ? util.bind(fn.render, fn) : fn; }; /** * Adds a child view(s) to another Module. * * Options: * * - `at` The child index at which to insert * - `inject` Injects the child's view element into the parent's * - `slot` The slot at which to insert the child * * @param {Module|Object} children * @param {Object|String|Number} options|slot */ proto.add = function(child, options) { if (!child) return this; // Options var at = options && options.at; var inject = options && options.inject; var slot = ('object' === typeof options) ? options.slot : options; // Remove this view first if it already has a parent if (child.parent) child.remove({ fromDOM: false }); // Assign a slot (prefering defined option) slot = child.slot = slot || child.slot; // Remove any module that already occupies this slot var resident = this.slots[slot]; if (resident) resident.remove({ fromDOM: false }); // If it's not a Module, make it one. if (!(child instanceof Module)) child = fm(child); util.insert(child, this.children, at); this._addLookup(child); // We append the child to the parent view if there is a view // element and the users hasn't flagged `append` false. if (inject) this._injectEl(child.el, options); // Allow chaining return this; }; /** * Removes a child view from * its current Module contexts * and also from the DOM unless * otherwise stated. * * Options: * * - `fromDOM` Whether the element should be removed from the DOM (default `true`) * * Example: * * // The following are equal * // apple is removed from the * // the view structure and DOM * layout.remove(apple); * apple.remove(); * * // Apple is removed from the * // view structure, but not the DOM * layout.remove(apple, { el: false }); * apple.remove({ el: false }); * * @return {FruitMachine} * @api public */ proto.remove = function(param1, param2) { // Don't do anything if the first arg is undefined if (arguments.length === 1 && !param1) return this; // Allow view.remove(child[, options]) // and view.remove([options]); if (param1 instanceof Module) { param1.remove(param2 || {}); return this; } // Options and aliases var options = param1 || {}; var fromDOM = options.fromDOM !== false; var parent = this.parent; var el = this.el; var parentNode = el && el.parentNode; var index; // Unless stated otherwise, // remove the view element // from its parent node. if (fromDOM && parentNode) { parentNode.removeChild(el); this._unmount(); } if (parent) { // Remove reference from views array index = parent.children.indexOf(this); parent.children.splice(index, 1); // Remove references from the lookup parent._removeLookup(this); } return this; }; /** * Creates a lookup reference for * the child view passed. * * @param {Module} child * @api private */ proto._addLookup = function(child) { var module = child.module(); // Add a lookup for module (this._modules[module] = this._modules[module] || []).push(child); // Add a lookup for id this._ids[child.id()] = child; // Store a reference by slot if (child.slot) this.slots[child.slot] = child; child.parent = this; }; /** * Removes the lookup for the * the child view passed. * * @param {Module} child * @api private */ proto._removeLookup = function(child) { var module = child.module(); // Remove the module lookup var index = this._modules[module].indexOf(child); this._modules[module].splice(index, 1); // Remove the id and slot lookup delete this._ids[child._id]; delete this.slots[child.slot]; delete child.parent; }; /** * Injects an element into the * Module's root element. * * By default the element is appended. * * Options: * * - `at` The index at which to insert. * * @param {Element} el * @param {Object} options * @api private */ proto._injectEl = function(el, options) { var at = options && options.at; var parent = this.el; if (!el || !parent) return; if (typeof at !== 'undefined') { parent.insertBefore(el, parent.children[at]); } else { parent.appendChild(el); } }; /** * Returns a decendent module * by id, or if called with no * arguments, returns this view's id. * * Example: * * myModule.id(); * //=> 'my_view_id' * * myModule.id('my_other_views_id'); * //=> Module * * @param {String|undefined} id * @return {Module|String} * @api public */ proto.id = function(id) { if (!arguments.length) return this._id; var child = this._ids[id]; if (child) return child; return this.each(function(view) { return view.id(id); }); }; /** * Returns the first descendent * Module with the passed module type. * If called with no arguments the * Module's own module type is returned. * * Example: * * // Assuming 'myModule' has 3 descendent * // views with the module type 'apple' * * myModule.modules('apple'); * //=> Module * * @param {String} key * @return {Module} */ proto.module = function(key) { if (!arguments.length) return this._module || this.name; var view = this._modules[key]; if (view && view.length) return view[0]; return this.each(function(view) { return view.module(key); }); }; /** * Returns a list of descendent * Modules that match the module * type given (Similar to * Element.querySelectorAll();). * * Example: * * // Assuming 'myModule' has 3 descendent * // views with the module type 'apple' * * myModule.modules('apple'); * //=> [ Module, Module, Module ] * * @param {String} key * @return {Array} * @api public */ proto.modules = function(key) { var list = this._modules[key] || []; // Then loop each child and run the // same opperation, appending the result // onto the list. this.each(function(view) { list = list.concat(view.modules(key)); }); return list; }; /** * Calls the passed function * for each of the view's * children. * * Example: * * myModule.each(function(child) { * // Do stuff with each child view... * }); * * @param {Function} fn * @return {[type]} */ proto.each = function(fn) { var l = this.children.length; var result; for (var i = 0; i < l; i++) { result = fn(this.children[i]); if (result) return result; } }; /** * Templates the view, including * any descendent views returning * an html string. All data in the * views model is made accessible * to the template. * * Child views are printed into the * parent template by `id`. Alternatively * children can be iterated over a a list * and printed with `{{{child}}}}`. * * Example: * * <div class="slot-1">{{{<slot>}}}</div> * <div class="slot-2">{{{<slot>}}}</div> * * // or * * {{#children}} * {{{child}}} * {{/children}} * * @return {String} * @api public */ proto.toHTML = function() { var html = this._innerHTML(); // Wrap the html in a FruitMachine // generated root element and return. return this._wrapHTML(html); }; /** * Get the view's innerHTML * * @return {String} */ proto._innerHTML = function() { this.fireStatic('before tohtml'); var data = {}; var html; var tmp; // Create an array for view // children data needed in template. data[fm.config.templateIterator] = []; // Loop each child this.each(function(child) { if (!child.model) { var err = new Error("Child without a model"); err.context = child; throw err; } tmp = {}; html = child.toHTML(); data[child.slot || child.id()] = html; tmp[fm.config.templateInstance] = html; data.children.push(mixin(tmp, child.model.toJSON())); }); // Run the template render method // passing children data (for looping // or child views) mixed with the // view's model data. return this.template ? this.template(mixin(data, this.model.toJSON())) : ''; }; /** * Wraps the module html in * a root element. * * @param {String} html var html = this.toHTML(); var el = util.toNode(html); // Sets a new element as a view's // root element (purging descendent // element caches). this._setEl(el); // Fetch all child module elements this._fetchEls(this.el); }; /** * Renders the view and replaces * the `view.el` with a freshly * rendered node. * * Fires a `render` event on the view. * * @return {Module} */ proto.render = function() { this.fireStatic('before render'); // If possible recycle outer element but // build from scratch if there is no // existing element or if tag changed var el = this.el; var classes; if (el && el.tagName === this.tag.toUpperCase()) { el.innerHTML = this._innerHTML(); this._unmountChildren(); classes = el.className.split(/\s+/); this._classes().forEach(function(add) { if (!~classes.indexOf(add)) el.className = el.className + ' ' + add; }); // Sets a new element as a view's // root element (purging descendent // element caches). } else { this._setEl(util.toNode(this.toHTML())); } // Fetch all child module elements this._fetchEls(this.el); // Handy hook this.fireStatic('render'); return this; }; /** * Sets up a view and all descendent * views. * * Setup will be aborted if no `view.el` * is found. If a view is already setup, * teardown is run first to prevent a * view being setup twice. * * Your custom `setup()` method is called * * Options: * * - `shallow` Does not recurse when `true` (default `false`) * * @param {Object} options * @return {Module} */ proto.setup = function(options) { var shallow = options && options.shallow; // Attempt to fetch the view's // root element. Don't continue // if no route element is found. if (!this._getEl()) return this; // If this is already setup, call // `teardown` first so that we don't // duplicate event bindings and shizzle. if (this.isSetup) this.teardown({ shallow: true }); // Fire the `setup` event hook this.fireStatic('before setup'); if (this._setup) this._setup(); this.fireStatic('setup'); // Flag view as 'setup' this.isSetup = true; // Call 'setup' on all subviews // first (top down recursion) if (!shallow) { this.each(function(child) { child.setup(); }); } // For chaining return this; }; /** * Tearsdown a view and all descendent * views that have been setup. * * Your custom `teardown` method is * called and a `teardown` event is fired. * * Options: * * - `shallow` Does not recurse when `true` (default `false`) * * @param {Object} options * @return {Module} */ proto.teardown = function(options) { var shallow = options && options.shallow; // Call 'setup' on all subviews // first (bottom up recursion). if (!shallow) { this.each(function(child) { child.teardown(); }); } // Only teardown if this view // has been setup. Teardown // is supposed to undo all the // work setup does, and therefore // will likely run into undefined // variables if setup hasn't run. if (this.isSetup) { this.fireStatic('before teardown'); if (this._teardown) this._teardown(); this.fireStatic('teardown'); this.isSetup = false; } // For chaining return this; }; /** * Completely destroys a view. This means * a view is torn down, removed from it's * current layout context and removed * from the DOM. * * Your custom `destroy` method is * called and a `destroy` event is fired. * * NOTE: `.remove()` is only run on the view * that `.destroy()` is directly called on. * * Options: * * - `fromDOM` Whether the view should be removed from DOM (default `true`) * * @api public */ proto.destroy = function(options) { options = options || {}; var remove = options.remove !== false; var l = this.children.length; // Destroy each child view. // We don't waste time removing // the child elements as they will // get removed when the parent // element is removed. // // We can't use the standard Module#each() // as the array length gets altered // with each iteration, hense the // reverse while loop. while (l--) { this.children[l].destroy({ remove: false }); } // Don't continue if this view // has already been destroyed. if (this.destroyed) return this; // .remove() is only run on the view that // destroy() was called on. // // It is a waste of time to remove the // descendent views as well, as any // references to them will get wiped // within destroy and they will get // removed from the DOM with the main view. if (remove) this.remove(options); // Run teardown this.teardown({ shallow: true }); // Fire an event hook before the // custom destroy logic is run this.fireStatic('before destroy'); // If custom destroy logic has been // defined on the prototype then run it. if (this._destroy) this._destroy(); // Trigger a `destroy` event // for custom Modules to bind to. this.fireStatic('destroy'); // Unbind any old event listeners this.off(); // Set a flag to say this view // has been destroyed. This is // useful to check for after a // slow ajax call that might come // back after a view has been detroyed. this.destroyed = true; // Clear references this.el = this.model = this.parent = this._modules = this._ids = this._id = null; }; /** * Destroys all children. * * Is this needed? * * @return {Module} * @api public */ proto.empty = function() { var l = this.children.length; while (l--) this.children[l].destroy(); return this; }; /** * Fetches all descendant elements * from the given root element. * * @param {Element} root * @return {undefined} * @api private */ proto._fetchEls = function(root) { if (!root) return; this.each(function(child) { child.mount(util.byId(child._fmid, root)); child._fetchEls(child.el || root); }); }; /** * Associate the view with an element. * Provide events and lifecycle methods * to fire when the element is newly * associated. * * @param {Element} el * @return {Element} */ proto.mount = function(el) { if(this.el !== el) { this.fireStatic('before mount'); this.el = el; if(this._mount) this._mount(); this.fireStatic('mount'); } return this.el; }; /** * Recursively fire unmount events on * children. To be called when a view's * children are implicitly removed from * the DOM (e.g. setting innerHTML) * * @api private */ proto._unmountChildren = function() { this.each(function(child) { child._unmount(); }); }; /*_setEl * Recursively fire unmount events on * a view and its children. To be * called when a view'is implicitly * removed from the DOM (e.g. _setEl) * * @api private */ proto._unmount = function() { this._unmountChildren(); this.fireStatic('unmount'); } /** * Returns the Module's root element. * * If a cache is present it is used, * else we search the DOM, else we * find the closest element and * perform a querySelector using * the view._fmid. * * @return {Element|undefined} * @api private */ proto._getEl = function() { if (!util.hasDom()) return; return this.mount(this.el || document.getElementById(this._fmid) || undefined); }; /** * Sets a root element on a view. * If the view already has a root * element, it is replaced. * * IMPORTANT: All descendent root * element caches are purged so that * the new correct elements are retrieved * next time Module#getElement is called. * * @param {Element} el * @return {Module} * @api private */ proto._setEl = function(el) { var existing = this.el; var parentNode = existing && existing.parentNode; // If the existing element has a context, replace it if (parentNode) { parentNode.replaceChild(el, existing); this._unmount(); } // Update cache this.mount(el); return this; }; /** * Empties the destination element * and appends the view into it. * * @param {Element} dest * @return {Module} * @api public */ proto.inject = function(dest) { if (dest) { dest.innerHTML = ''; this.insertBefore(dest, null); this.fireStatic('inject'); } return this; }; /** * Appends the view element into * the destination element. * * @param {Element} dest * @return {Module} * @api public */ proto.appendTo = function(dest) { return this.insertBefore(dest, null); }; /** * Inserts the view element before the * given child of the destination element. * * @param {Element} dest * @param {Element} beforeEl * @return {Module} * @api public */ proto.insertBefore = function(dest, beforeEl) { if (this.el && dest && dest.insertBefore) { dest.insertBefore(this.el, beforeEl); // This badly-named event is for legacy reasons; perhaps 'insert' would be better here? this.fireStatic('appendto'); } return this; }; /** * Returns a JSON represention of * a FruitMachine Module. This can * be generated serverside and * passed into new FruitMachine(json) * to inflate serverside rendered * views. * * @return {Object} * @api public */ proto.toJSON = function() { var json = {}; json.children = []; // Recurse this.each(function(child) { json.children.push(child.toJSON()); }); json.id = this.id(); json.fmid = this._fmid; json.module = this.module(); json.model = this.model.toJSON(); json.slot = this.slot; // Fire a hook to allow third // parties to alter the json output this.fireStatic('tojson', json); return json; }; // Events proto.on = events.on; proto.off = events.off; proto.fire = events.fire; proto.fireStatic = events.fireStatic; // Allow Modules to be extended Module.extend = extend(util.keys(proto)); // Adding proto.Model after // Module.extend means this // key can be overwritten. proto.Model = fm.Model; return Module; }; <MSG> Actually recycle DOM outer layer DOM node between renders <DFF> @@ -529,10 +529,16 @@ module.exports = function(fm) { var html = this.toHTML(); var el = util.toNode(html); - // Sets a new element as a view's - // root element (purging descendent - // element caches). - this._setEl(el); + // If possible recycle outer element + if (this.el) { + this.el.innerHTML = el.innerHTML; + } else { + + // Sets a new element as a view's + // root element (purging descendent + // element caches). + this._setEl(el); + } // Fetch all child module elements this._fetchEls(this.el);
10
Actually recycle DOM outer layer DOM node between renders
4
.js
js
mit
ftlabs/fruitmachine