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
10068050
<NME> Resources.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.IO; using System.Reflection; // ReSharper disable once CheckNamespace namespace AvaloniaEdit.Highlighting { internal static class Resources { private const string Prefix = "AvaloniaEdit.Highlighting.Resources."; public static Stream OpenStream(string name) { var s = typeof(Resources).GetTypeInfo().Assembly.GetManifestResourceStream(Prefix + name); if (s == null) throw new FileNotFoundException("The resource file '" + name + "' was not found."); return s; } internal static void RegisterBuiltInHighlightings(HighlightingManager.DefaultHighlightingManager hlm) { hlm.RegisterHighlighting("XmlDoc", null, "XmlDoc.xshd"); hlm.RegisterHighlighting("C#", new[] { ".cs" }, "CSharp-Mode.xshd"); hlm.RegisterHighlighting("JavaScript", new[] { ".js" }, "JavaScript-Mode.xshd"); hlm.RegisterHighlighting("HTML", new[] { ".htm", ".html" }, "HTML-Mode.xshd"); hlm.RegisterHighlighting("ASP/XHTML", new[] { ".asp", ".aspx", ".asax", ".asmx", ".ascx", ".master" }, "ASPX.xshd"); hlm.RegisterHighlighting("Boo", new[] { ".boo" }, "Boo.xshd"); hlm.RegisterHighlighting("Coco", new[] { ".atg" }, "Coco-Mode.xshd"); hlm.RegisterHighlighting("CSS", new[] { ".css" }, "CSS-Mode.xshd"); hlm.RegisterHighlighting("C++", new[] { ".c", ".h", ".cc", ".cpp", ".hpp" }, "CPP-Mode.xshd"); hlm.RegisterHighlighting("Java", new[] { ".java" }, "Java-Mode.xshd"); hlm.RegisterHighlighting("Patch", new[] { ".patch", ".diff" }, "Patch-Mode.xshd"); hlm.RegisterHighlighting("PowerShell", new[] { ".ps1", ".psm1", ".psd1" }, "PowerShell.xshd"); hlm.RegisterHighlighting("PHP", new[] { ".php" }, "PHP-Mode.xshd"); hlm.RegisterHighlighting("Python", new[] { ".py", ".pyw" }, "Python-Mode.xshd"); hlm.RegisterHighlighting("TeX", new[] { ".tex" }, "Tex-Mode.xshd"); hlm.RegisterHighlighting("TSQL", new[] { ".sql" }, "TSQL-Mode.xshd"); hlm.RegisterHighlighting("VB", new[] { ".vb" }, "VB-Mode.xshd"); ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } } hlm.RegisterHighlighting("Json", new[] { ".json" }, "Json.xshd"); } } } <MSG> fix xaml highlighting support <DFF> @@ -58,7 +58,7 @@ namespace AvaloniaEdit.Highlighting ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); - hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); + hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-Mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } }
1
fix xaml highlighting support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068051
<NME> Resources.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.IO; using System.Reflection; // ReSharper disable once CheckNamespace namespace AvaloniaEdit.Highlighting { internal static class Resources { private const string Prefix = "AvaloniaEdit.Highlighting.Resources."; public static Stream OpenStream(string name) { var s = typeof(Resources).GetTypeInfo().Assembly.GetManifestResourceStream(Prefix + name); if (s == null) throw new FileNotFoundException("The resource file '" + name + "' was not found."); return s; } internal static void RegisterBuiltInHighlightings(HighlightingManager.DefaultHighlightingManager hlm) { hlm.RegisterHighlighting("XmlDoc", null, "XmlDoc.xshd"); hlm.RegisterHighlighting("C#", new[] { ".cs" }, "CSharp-Mode.xshd"); hlm.RegisterHighlighting("JavaScript", new[] { ".js" }, "JavaScript-Mode.xshd"); hlm.RegisterHighlighting("HTML", new[] { ".htm", ".html" }, "HTML-Mode.xshd"); hlm.RegisterHighlighting("ASP/XHTML", new[] { ".asp", ".aspx", ".asax", ".asmx", ".ascx", ".master" }, "ASPX.xshd"); hlm.RegisterHighlighting("Boo", new[] { ".boo" }, "Boo.xshd"); hlm.RegisterHighlighting("Coco", new[] { ".atg" }, "Coco-Mode.xshd"); hlm.RegisterHighlighting("CSS", new[] { ".css" }, "CSS-Mode.xshd"); hlm.RegisterHighlighting("C++", new[] { ".c", ".h", ".cc", ".cpp", ".hpp" }, "CPP-Mode.xshd"); hlm.RegisterHighlighting("Java", new[] { ".java" }, "Java-Mode.xshd"); hlm.RegisterHighlighting("Patch", new[] { ".patch", ".diff" }, "Patch-Mode.xshd"); hlm.RegisterHighlighting("PowerShell", new[] { ".ps1", ".psm1", ".psd1" }, "PowerShell.xshd"); hlm.RegisterHighlighting("PHP", new[] { ".php" }, "PHP-Mode.xshd"); hlm.RegisterHighlighting("Python", new[] { ".py", ".pyw" }, "Python-Mode.xshd"); hlm.RegisterHighlighting("TeX", new[] { ".tex" }, "Tex-Mode.xshd"); hlm.RegisterHighlighting("TSQL", new[] { ".sql" }, "TSQL-Mode.xshd"); hlm.RegisterHighlighting("VB", new[] { ".vb" }, "VB-Mode.xshd"); ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } } hlm.RegisterHighlighting("Json", new[] { ".json" }, "Json.xshd"); } } } <MSG> fix xaml highlighting support <DFF> @@ -58,7 +58,7 @@ namespace AvaloniaEdit.Highlighting ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); - hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); + hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-Mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } }
1
fix xaml highlighting support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068052
<NME> Resources.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.IO; using System.Reflection; // ReSharper disable once CheckNamespace namespace AvaloniaEdit.Highlighting { internal static class Resources { private const string Prefix = "AvaloniaEdit.Highlighting.Resources."; public static Stream OpenStream(string name) { var s = typeof(Resources).GetTypeInfo().Assembly.GetManifestResourceStream(Prefix + name); if (s == null) throw new FileNotFoundException("The resource file '" + name + "' was not found."); return s; } internal static void RegisterBuiltInHighlightings(HighlightingManager.DefaultHighlightingManager hlm) { hlm.RegisterHighlighting("XmlDoc", null, "XmlDoc.xshd"); hlm.RegisterHighlighting("C#", new[] { ".cs" }, "CSharp-Mode.xshd"); hlm.RegisterHighlighting("JavaScript", new[] { ".js" }, "JavaScript-Mode.xshd"); hlm.RegisterHighlighting("HTML", new[] { ".htm", ".html" }, "HTML-Mode.xshd"); hlm.RegisterHighlighting("ASP/XHTML", new[] { ".asp", ".aspx", ".asax", ".asmx", ".ascx", ".master" }, "ASPX.xshd"); hlm.RegisterHighlighting("Boo", new[] { ".boo" }, "Boo.xshd"); hlm.RegisterHighlighting("Coco", new[] { ".atg" }, "Coco-Mode.xshd"); hlm.RegisterHighlighting("CSS", new[] { ".css" }, "CSS-Mode.xshd"); hlm.RegisterHighlighting("C++", new[] { ".c", ".h", ".cc", ".cpp", ".hpp" }, "CPP-Mode.xshd"); hlm.RegisterHighlighting("Java", new[] { ".java" }, "Java-Mode.xshd"); hlm.RegisterHighlighting("Patch", new[] { ".patch", ".diff" }, "Patch-Mode.xshd"); hlm.RegisterHighlighting("PowerShell", new[] { ".ps1", ".psm1", ".psd1" }, "PowerShell.xshd"); hlm.RegisterHighlighting("PHP", new[] { ".php" }, "PHP-Mode.xshd"); hlm.RegisterHighlighting("Python", new[] { ".py", ".pyw" }, "Python-Mode.xshd"); hlm.RegisterHighlighting("TeX", new[] { ".tex" }, "Tex-Mode.xshd"); hlm.RegisterHighlighting("TSQL", new[] { ".sql" }, "TSQL-Mode.xshd"); hlm.RegisterHighlighting("VB", new[] { ".vb" }, "VB-Mode.xshd"); ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } } hlm.RegisterHighlighting("Json", new[] { ".json" }, "Json.xshd"); } } } <MSG> fix xaml highlighting support <DFF> @@ -58,7 +58,7 @@ namespace AvaloniaEdit.Highlighting ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); - hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); + hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-Mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } }
1
fix xaml highlighting support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068053
<NME> Resources.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.IO; using System.Reflection; // ReSharper disable once CheckNamespace namespace AvaloniaEdit.Highlighting { internal static class Resources { private const string Prefix = "AvaloniaEdit.Highlighting.Resources."; public static Stream OpenStream(string name) { var s = typeof(Resources).GetTypeInfo().Assembly.GetManifestResourceStream(Prefix + name); if (s == null) throw new FileNotFoundException("The resource file '" + name + "' was not found."); return s; } internal static void RegisterBuiltInHighlightings(HighlightingManager.DefaultHighlightingManager hlm) { hlm.RegisterHighlighting("XmlDoc", null, "XmlDoc.xshd"); hlm.RegisterHighlighting("C#", new[] { ".cs" }, "CSharp-Mode.xshd"); hlm.RegisterHighlighting("JavaScript", new[] { ".js" }, "JavaScript-Mode.xshd"); hlm.RegisterHighlighting("HTML", new[] { ".htm", ".html" }, "HTML-Mode.xshd"); hlm.RegisterHighlighting("ASP/XHTML", new[] { ".asp", ".aspx", ".asax", ".asmx", ".ascx", ".master" }, "ASPX.xshd"); hlm.RegisterHighlighting("Boo", new[] { ".boo" }, "Boo.xshd"); hlm.RegisterHighlighting("Coco", new[] { ".atg" }, "Coco-Mode.xshd"); hlm.RegisterHighlighting("CSS", new[] { ".css" }, "CSS-Mode.xshd"); hlm.RegisterHighlighting("C++", new[] { ".c", ".h", ".cc", ".cpp", ".hpp" }, "CPP-Mode.xshd"); hlm.RegisterHighlighting("Java", new[] { ".java" }, "Java-Mode.xshd"); hlm.RegisterHighlighting("Patch", new[] { ".patch", ".diff" }, "Patch-Mode.xshd"); hlm.RegisterHighlighting("PowerShell", new[] { ".ps1", ".psm1", ".psd1" }, "PowerShell.xshd"); hlm.RegisterHighlighting("PHP", new[] { ".php" }, "PHP-Mode.xshd"); hlm.RegisterHighlighting("Python", new[] { ".py", ".pyw" }, "Python-Mode.xshd"); hlm.RegisterHighlighting("TeX", new[] { ".tex" }, "Tex-Mode.xshd"); hlm.RegisterHighlighting("TSQL", new[] { ".sql" }, "TSQL-Mode.xshd"); hlm.RegisterHighlighting("VB", new[] { ".vb" }, "VB-Mode.xshd"); ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } } hlm.RegisterHighlighting("Json", new[] { ".json" }, "Json.xshd"); } } } <MSG> fix xaml highlighting support <DFF> @@ -58,7 +58,7 @@ namespace AvaloniaEdit.Highlighting ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); - hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); + hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-Mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } }
1
fix xaml highlighting support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068054
<NME> Resources.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.IO; using System.Reflection; // ReSharper disable once CheckNamespace namespace AvaloniaEdit.Highlighting { internal static class Resources { private const string Prefix = "AvaloniaEdit.Highlighting.Resources."; public static Stream OpenStream(string name) { var s = typeof(Resources).GetTypeInfo().Assembly.GetManifestResourceStream(Prefix + name); if (s == null) throw new FileNotFoundException("The resource file '" + name + "' was not found."); return s; } internal static void RegisterBuiltInHighlightings(HighlightingManager.DefaultHighlightingManager hlm) { hlm.RegisterHighlighting("XmlDoc", null, "XmlDoc.xshd"); hlm.RegisterHighlighting("C#", new[] { ".cs" }, "CSharp-Mode.xshd"); hlm.RegisterHighlighting("JavaScript", new[] { ".js" }, "JavaScript-Mode.xshd"); hlm.RegisterHighlighting("HTML", new[] { ".htm", ".html" }, "HTML-Mode.xshd"); hlm.RegisterHighlighting("ASP/XHTML", new[] { ".asp", ".aspx", ".asax", ".asmx", ".ascx", ".master" }, "ASPX.xshd"); hlm.RegisterHighlighting("Boo", new[] { ".boo" }, "Boo.xshd"); hlm.RegisterHighlighting("Coco", new[] { ".atg" }, "Coco-Mode.xshd"); hlm.RegisterHighlighting("CSS", new[] { ".css" }, "CSS-Mode.xshd"); hlm.RegisterHighlighting("C++", new[] { ".c", ".h", ".cc", ".cpp", ".hpp" }, "CPP-Mode.xshd"); hlm.RegisterHighlighting("Java", new[] { ".java" }, "Java-Mode.xshd"); hlm.RegisterHighlighting("Patch", new[] { ".patch", ".diff" }, "Patch-Mode.xshd"); hlm.RegisterHighlighting("PowerShell", new[] { ".ps1", ".psm1", ".psd1" }, "PowerShell.xshd"); hlm.RegisterHighlighting("PHP", new[] { ".php" }, "PHP-Mode.xshd"); hlm.RegisterHighlighting("Python", new[] { ".py", ".pyw" }, "Python-Mode.xshd"); hlm.RegisterHighlighting("TeX", new[] { ".tex" }, "Tex-Mode.xshd"); hlm.RegisterHighlighting("TSQL", new[] { ".sql" }, "TSQL-Mode.xshd"); hlm.RegisterHighlighting("VB", new[] { ".vb" }, "VB-Mode.xshd"); ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } } hlm.RegisterHighlighting("Json", new[] { ".json" }, "Json.xshd"); } } } <MSG> fix xaml highlighting support <DFF> @@ -58,7 +58,7 @@ namespace AvaloniaEdit.Highlighting ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); - hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); + hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-Mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } }
1
fix xaml highlighting support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068055
<NME> Resources.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.IO; using System.Reflection; // ReSharper disable once CheckNamespace namespace AvaloniaEdit.Highlighting { internal static class Resources { private const string Prefix = "AvaloniaEdit.Highlighting.Resources."; public static Stream OpenStream(string name) { var s = typeof(Resources).GetTypeInfo().Assembly.GetManifestResourceStream(Prefix + name); if (s == null) throw new FileNotFoundException("The resource file '" + name + "' was not found."); return s; } internal static void RegisterBuiltInHighlightings(HighlightingManager.DefaultHighlightingManager hlm) { hlm.RegisterHighlighting("XmlDoc", null, "XmlDoc.xshd"); hlm.RegisterHighlighting("C#", new[] { ".cs" }, "CSharp-Mode.xshd"); hlm.RegisterHighlighting("JavaScript", new[] { ".js" }, "JavaScript-Mode.xshd"); hlm.RegisterHighlighting("HTML", new[] { ".htm", ".html" }, "HTML-Mode.xshd"); hlm.RegisterHighlighting("ASP/XHTML", new[] { ".asp", ".aspx", ".asax", ".asmx", ".ascx", ".master" }, "ASPX.xshd"); hlm.RegisterHighlighting("Boo", new[] { ".boo" }, "Boo.xshd"); hlm.RegisterHighlighting("Coco", new[] { ".atg" }, "Coco-Mode.xshd"); hlm.RegisterHighlighting("CSS", new[] { ".css" }, "CSS-Mode.xshd"); hlm.RegisterHighlighting("C++", new[] { ".c", ".h", ".cc", ".cpp", ".hpp" }, "CPP-Mode.xshd"); hlm.RegisterHighlighting("Java", new[] { ".java" }, "Java-Mode.xshd"); hlm.RegisterHighlighting("Patch", new[] { ".patch", ".diff" }, "Patch-Mode.xshd"); hlm.RegisterHighlighting("PowerShell", new[] { ".ps1", ".psm1", ".psd1" }, "PowerShell.xshd"); hlm.RegisterHighlighting("PHP", new[] { ".php" }, "PHP-Mode.xshd"); hlm.RegisterHighlighting("Python", new[] { ".py", ".pyw" }, "Python-Mode.xshd"); hlm.RegisterHighlighting("TeX", new[] { ".tex" }, "Tex-Mode.xshd"); hlm.RegisterHighlighting("TSQL", new[] { ".sql" }, "TSQL-Mode.xshd"); hlm.RegisterHighlighting("VB", new[] { ".vb" }, "VB-Mode.xshd"); ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } } hlm.RegisterHighlighting("Json", new[] { ".json" }, "Json.xshd"); } } } <MSG> fix xaml highlighting support <DFF> @@ -58,7 +58,7 @@ namespace AvaloniaEdit.Highlighting ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); - hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); + hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-Mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } }
1
fix xaml highlighting support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068056
<NME> Resources.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.IO; using System.Reflection; // ReSharper disable once CheckNamespace namespace AvaloniaEdit.Highlighting { internal static class Resources { private const string Prefix = "AvaloniaEdit.Highlighting.Resources."; public static Stream OpenStream(string name) { var s = typeof(Resources).GetTypeInfo().Assembly.GetManifestResourceStream(Prefix + name); if (s == null) throw new FileNotFoundException("The resource file '" + name + "' was not found."); return s; } internal static void RegisterBuiltInHighlightings(HighlightingManager.DefaultHighlightingManager hlm) { hlm.RegisterHighlighting("XmlDoc", null, "XmlDoc.xshd"); hlm.RegisterHighlighting("C#", new[] { ".cs" }, "CSharp-Mode.xshd"); hlm.RegisterHighlighting("JavaScript", new[] { ".js" }, "JavaScript-Mode.xshd"); hlm.RegisterHighlighting("HTML", new[] { ".htm", ".html" }, "HTML-Mode.xshd"); hlm.RegisterHighlighting("ASP/XHTML", new[] { ".asp", ".aspx", ".asax", ".asmx", ".ascx", ".master" }, "ASPX.xshd"); hlm.RegisterHighlighting("Boo", new[] { ".boo" }, "Boo.xshd"); hlm.RegisterHighlighting("Coco", new[] { ".atg" }, "Coco-Mode.xshd"); hlm.RegisterHighlighting("CSS", new[] { ".css" }, "CSS-Mode.xshd"); hlm.RegisterHighlighting("C++", new[] { ".c", ".h", ".cc", ".cpp", ".hpp" }, "CPP-Mode.xshd"); hlm.RegisterHighlighting("Java", new[] { ".java" }, "Java-Mode.xshd"); hlm.RegisterHighlighting("Patch", new[] { ".patch", ".diff" }, "Patch-Mode.xshd"); hlm.RegisterHighlighting("PowerShell", new[] { ".ps1", ".psm1", ".psd1" }, "PowerShell.xshd"); hlm.RegisterHighlighting("PHP", new[] { ".php" }, "PHP-Mode.xshd"); hlm.RegisterHighlighting("Python", new[] { ".py", ".pyw" }, "Python-Mode.xshd"); hlm.RegisterHighlighting("TeX", new[] { ".tex" }, "Tex-Mode.xshd"); hlm.RegisterHighlighting("TSQL", new[] { ".sql" }, "TSQL-Mode.xshd"); hlm.RegisterHighlighting("VB", new[] { ".vb" }, "VB-Mode.xshd"); ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } } hlm.RegisterHighlighting("Json", new[] { ".json" }, "Json.xshd"); } } } <MSG> fix xaml highlighting support <DFF> @@ -58,7 +58,7 @@ namespace AvaloniaEdit.Highlighting ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); - hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); + hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-Mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } }
1
fix xaml highlighting support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068057
<NME> Resources.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.IO; using System.Reflection; // ReSharper disable once CheckNamespace namespace AvaloniaEdit.Highlighting { internal static class Resources { private const string Prefix = "AvaloniaEdit.Highlighting.Resources."; public static Stream OpenStream(string name) { var s = typeof(Resources).GetTypeInfo().Assembly.GetManifestResourceStream(Prefix + name); if (s == null) throw new FileNotFoundException("The resource file '" + name + "' was not found."); return s; } internal static void RegisterBuiltInHighlightings(HighlightingManager.DefaultHighlightingManager hlm) { hlm.RegisterHighlighting("XmlDoc", null, "XmlDoc.xshd"); hlm.RegisterHighlighting("C#", new[] { ".cs" }, "CSharp-Mode.xshd"); hlm.RegisterHighlighting("JavaScript", new[] { ".js" }, "JavaScript-Mode.xshd"); hlm.RegisterHighlighting("HTML", new[] { ".htm", ".html" }, "HTML-Mode.xshd"); hlm.RegisterHighlighting("ASP/XHTML", new[] { ".asp", ".aspx", ".asax", ".asmx", ".ascx", ".master" }, "ASPX.xshd"); hlm.RegisterHighlighting("Boo", new[] { ".boo" }, "Boo.xshd"); hlm.RegisterHighlighting("Coco", new[] { ".atg" }, "Coco-Mode.xshd"); hlm.RegisterHighlighting("CSS", new[] { ".css" }, "CSS-Mode.xshd"); hlm.RegisterHighlighting("C++", new[] { ".c", ".h", ".cc", ".cpp", ".hpp" }, "CPP-Mode.xshd"); hlm.RegisterHighlighting("Java", new[] { ".java" }, "Java-Mode.xshd"); hlm.RegisterHighlighting("Patch", new[] { ".patch", ".diff" }, "Patch-Mode.xshd"); hlm.RegisterHighlighting("PowerShell", new[] { ".ps1", ".psm1", ".psd1" }, "PowerShell.xshd"); hlm.RegisterHighlighting("PHP", new[] { ".php" }, "PHP-Mode.xshd"); hlm.RegisterHighlighting("Python", new[] { ".py", ".pyw" }, "Python-Mode.xshd"); hlm.RegisterHighlighting("TeX", new[] { ".tex" }, "Tex-Mode.xshd"); hlm.RegisterHighlighting("TSQL", new[] { ".sql" }, "TSQL-Mode.xshd"); hlm.RegisterHighlighting("VB", new[] { ".vb" }, "VB-Mode.xshd"); ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } } hlm.RegisterHighlighting("Json", new[] { ".json" }, "Json.xshd"); } } } <MSG> fix xaml highlighting support <DFF> @@ -58,7 +58,7 @@ namespace AvaloniaEdit.Highlighting ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); - hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); + hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-Mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } }
1
fix xaml highlighting support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068058
<NME> Resources.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.IO; using System.Reflection; // ReSharper disable once CheckNamespace namespace AvaloniaEdit.Highlighting { internal static class Resources { private const string Prefix = "AvaloniaEdit.Highlighting.Resources."; public static Stream OpenStream(string name) { var s = typeof(Resources).GetTypeInfo().Assembly.GetManifestResourceStream(Prefix + name); if (s == null) throw new FileNotFoundException("The resource file '" + name + "' was not found."); return s; } internal static void RegisterBuiltInHighlightings(HighlightingManager.DefaultHighlightingManager hlm) { hlm.RegisterHighlighting("XmlDoc", null, "XmlDoc.xshd"); hlm.RegisterHighlighting("C#", new[] { ".cs" }, "CSharp-Mode.xshd"); hlm.RegisterHighlighting("JavaScript", new[] { ".js" }, "JavaScript-Mode.xshd"); hlm.RegisterHighlighting("HTML", new[] { ".htm", ".html" }, "HTML-Mode.xshd"); hlm.RegisterHighlighting("ASP/XHTML", new[] { ".asp", ".aspx", ".asax", ".asmx", ".ascx", ".master" }, "ASPX.xshd"); hlm.RegisterHighlighting("Boo", new[] { ".boo" }, "Boo.xshd"); hlm.RegisterHighlighting("Coco", new[] { ".atg" }, "Coco-Mode.xshd"); hlm.RegisterHighlighting("CSS", new[] { ".css" }, "CSS-Mode.xshd"); hlm.RegisterHighlighting("C++", new[] { ".c", ".h", ".cc", ".cpp", ".hpp" }, "CPP-Mode.xshd"); hlm.RegisterHighlighting("Java", new[] { ".java" }, "Java-Mode.xshd"); hlm.RegisterHighlighting("Patch", new[] { ".patch", ".diff" }, "Patch-Mode.xshd"); hlm.RegisterHighlighting("PowerShell", new[] { ".ps1", ".psm1", ".psd1" }, "PowerShell.xshd"); hlm.RegisterHighlighting("PHP", new[] { ".php" }, "PHP-Mode.xshd"); hlm.RegisterHighlighting("Python", new[] { ".py", ".pyw" }, "Python-Mode.xshd"); hlm.RegisterHighlighting("TeX", new[] { ".tex" }, "Tex-Mode.xshd"); hlm.RegisterHighlighting("TSQL", new[] { ".sql" }, "TSQL-Mode.xshd"); hlm.RegisterHighlighting("VB", new[] { ".vb" }, "VB-Mode.xshd"); ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } } hlm.RegisterHighlighting("Json", new[] { ".json" }, "Json.xshd"); } } } <MSG> fix xaml highlighting support <DFF> @@ -58,7 +58,7 @@ namespace AvaloniaEdit.Highlighting ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); - hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); + hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-Mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } }
1
fix xaml highlighting support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068059
<NME> Resources.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.IO; using System.Reflection; // ReSharper disable once CheckNamespace namespace AvaloniaEdit.Highlighting { internal static class Resources { private const string Prefix = "AvaloniaEdit.Highlighting.Resources."; public static Stream OpenStream(string name) { var s = typeof(Resources).GetTypeInfo().Assembly.GetManifestResourceStream(Prefix + name); if (s == null) throw new FileNotFoundException("The resource file '" + name + "' was not found."); return s; } internal static void RegisterBuiltInHighlightings(HighlightingManager.DefaultHighlightingManager hlm) { hlm.RegisterHighlighting("XmlDoc", null, "XmlDoc.xshd"); hlm.RegisterHighlighting("C#", new[] { ".cs" }, "CSharp-Mode.xshd"); hlm.RegisterHighlighting("JavaScript", new[] { ".js" }, "JavaScript-Mode.xshd"); hlm.RegisterHighlighting("HTML", new[] { ".htm", ".html" }, "HTML-Mode.xshd"); hlm.RegisterHighlighting("ASP/XHTML", new[] { ".asp", ".aspx", ".asax", ".asmx", ".ascx", ".master" }, "ASPX.xshd"); hlm.RegisterHighlighting("Boo", new[] { ".boo" }, "Boo.xshd"); hlm.RegisterHighlighting("Coco", new[] { ".atg" }, "Coco-Mode.xshd"); hlm.RegisterHighlighting("CSS", new[] { ".css" }, "CSS-Mode.xshd"); hlm.RegisterHighlighting("C++", new[] { ".c", ".h", ".cc", ".cpp", ".hpp" }, "CPP-Mode.xshd"); hlm.RegisterHighlighting("Java", new[] { ".java" }, "Java-Mode.xshd"); hlm.RegisterHighlighting("Patch", new[] { ".patch", ".diff" }, "Patch-Mode.xshd"); hlm.RegisterHighlighting("PowerShell", new[] { ".ps1", ".psm1", ".psd1" }, "PowerShell.xshd"); hlm.RegisterHighlighting("PHP", new[] { ".php" }, "PHP-Mode.xshd"); hlm.RegisterHighlighting("Python", new[] { ".py", ".pyw" }, "Python-Mode.xshd"); hlm.RegisterHighlighting("TeX", new[] { ".tex" }, "Tex-Mode.xshd"); hlm.RegisterHighlighting("TSQL", new[] { ".sql" }, "TSQL-Mode.xshd"); hlm.RegisterHighlighting("VB", new[] { ".vb" }, "VB-Mode.xshd"); ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } } hlm.RegisterHighlighting("Json", new[] { ".json" }, "Json.xshd"); } } } <MSG> fix xaml highlighting support <DFF> @@ -58,7 +58,7 @@ namespace AvaloniaEdit.Highlighting ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); - hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); + hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-Mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } }
1
fix xaml highlighting support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068060
<NME> Resources.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.IO; using System.Reflection; // ReSharper disable once CheckNamespace namespace AvaloniaEdit.Highlighting { internal static class Resources { private const string Prefix = "AvaloniaEdit.Highlighting.Resources."; public static Stream OpenStream(string name) { var s = typeof(Resources).GetTypeInfo().Assembly.GetManifestResourceStream(Prefix + name); if (s == null) throw new FileNotFoundException("The resource file '" + name + "' was not found."); return s; } internal static void RegisterBuiltInHighlightings(HighlightingManager.DefaultHighlightingManager hlm) { hlm.RegisterHighlighting("XmlDoc", null, "XmlDoc.xshd"); hlm.RegisterHighlighting("C#", new[] { ".cs" }, "CSharp-Mode.xshd"); hlm.RegisterHighlighting("JavaScript", new[] { ".js" }, "JavaScript-Mode.xshd"); hlm.RegisterHighlighting("HTML", new[] { ".htm", ".html" }, "HTML-Mode.xshd"); hlm.RegisterHighlighting("ASP/XHTML", new[] { ".asp", ".aspx", ".asax", ".asmx", ".ascx", ".master" }, "ASPX.xshd"); hlm.RegisterHighlighting("Boo", new[] { ".boo" }, "Boo.xshd"); hlm.RegisterHighlighting("Coco", new[] { ".atg" }, "Coco-Mode.xshd"); hlm.RegisterHighlighting("CSS", new[] { ".css" }, "CSS-Mode.xshd"); hlm.RegisterHighlighting("C++", new[] { ".c", ".h", ".cc", ".cpp", ".hpp" }, "CPP-Mode.xshd"); hlm.RegisterHighlighting("Java", new[] { ".java" }, "Java-Mode.xshd"); hlm.RegisterHighlighting("Patch", new[] { ".patch", ".diff" }, "Patch-Mode.xshd"); hlm.RegisterHighlighting("PowerShell", new[] { ".ps1", ".psm1", ".psd1" }, "PowerShell.xshd"); hlm.RegisterHighlighting("PHP", new[] { ".php" }, "PHP-Mode.xshd"); hlm.RegisterHighlighting("Python", new[] { ".py", ".pyw" }, "Python-Mode.xshd"); hlm.RegisterHighlighting("TeX", new[] { ".tex" }, "Tex-Mode.xshd"); hlm.RegisterHighlighting("TSQL", new[] { ".sql" }, "TSQL-Mode.xshd"); hlm.RegisterHighlighting("VB", new[] { ".vb" }, "VB-Mode.xshd"); ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } } hlm.RegisterHighlighting("Json", new[] { ".json" }, "Json.xshd"); } } } <MSG> fix xaml highlighting support <DFF> @@ -58,7 +58,7 @@ namespace AvaloniaEdit.Highlighting ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); - hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); + hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-Mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } }
1
fix xaml highlighting support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068061
<NME> Resources.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.IO; using System.Reflection; // ReSharper disable once CheckNamespace namespace AvaloniaEdit.Highlighting { internal static class Resources { private const string Prefix = "AvaloniaEdit.Highlighting.Resources."; public static Stream OpenStream(string name) { var s = typeof(Resources).GetTypeInfo().Assembly.GetManifestResourceStream(Prefix + name); if (s == null) throw new FileNotFoundException("The resource file '" + name + "' was not found."); return s; } internal static void RegisterBuiltInHighlightings(HighlightingManager.DefaultHighlightingManager hlm) { hlm.RegisterHighlighting("XmlDoc", null, "XmlDoc.xshd"); hlm.RegisterHighlighting("C#", new[] { ".cs" }, "CSharp-Mode.xshd"); hlm.RegisterHighlighting("JavaScript", new[] { ".js" }, "JavaScript-Mode.xshd"); hlm.RegisterHighlighting("HTML", new[] { ".htm", ".html" }, "HTML-Mode.xshd"); hlm.RegisterHighlighting("ASP/XHTML", new[] { ".asp", ".aspx", ".asax", ".asmx", ".ascx", ".master" }, "ASPX.xshd"); hlm.RegisterHighlighting("Boo", new[] { ".boo" }, "Boo.xshd"); hlm.RegisterHighlighting("Coco", new[] { ".atg" }, "Coco-Mode.xshd"); hlm.RegisterHighlighting("CSS", new[] { ".css" }, "CSS-Mode.xshd"); hlm.RegisterHighlighting("C++", new[] { ".c", ".h", ".cc", ".cpp", ".hpp" }, "CPP-Mode.xshd"); hlm.RegisterHighlighting("Java", new[] { ".java" }, "Java-Mode.xshd"); hlm.RegisterHighlighting("Patch", new[] { ".patch", ".diff" }, "Patch-Mode.xshd"); hlm.RegisterHighlighting("PowerShell", new[] { ".ps1", ".psm1", ".psd1" }, "PowerShell.xshd"); hlm.RegisterHighlighting("PHP", new[] { ".php" }, "PHP-Mode.xshd"); hlm.RegisterHighlighting("Python", new[] { ".py", ".pyw" }, "Python-Mode.xshd"); hlm.RegisterHighlighting("TeX", new[] { ".tex" }, "Tex-Mode.xshd"); hlm.RegisterHighlighting("TSQL", new[] { ".sql" }, "TSQL-Mode.xshd"); hlm.RegisterHighlighting("VB", new[] { ".vb" }, "VB-Mode.xshd"); ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } } hlm.RegisterHighlighting("Json", new[] { ".json" }, "Json.xshd"); } } } <MSG> fix xaml highlighting support <DFF> @@ -58,7 +58,7 @@ namespace AvaloniaEdit.Highlighting ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); - hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); + hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-Mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } }
1
fix xaml highlighting support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068062
<NME> Resources.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.IO; using System.Reflection; // ReSharper disable once CheckNamespace namespace AvaloniaEdit.Highlighting { internal static class Resources { private const string Prefix = "AvaloniaEdit.Highlighting.Resources."; public static Stream OpenStream(string name) { var s = typeof(Resources).GetTypeInfo().Assembly.GetManifestResourceStream(Prefix + name); if (s == null) throw new FileNotFoundException("The resource file '" + name + "' was not found."); return s; } internal static void RegisterBuiltInHighlightings(HighlightingManager.DefaultHighlightingManager hlm) { hlm.RegisterHighlighting("XmlDoc", null, "XmlDoc.xshd"); hlm.RegisterHighlighting("C#", new[] { ".cs" }, "CSharp-Mode.xshd"); hlm.RegisterHighlighting("JavaScript", new[] { ".js" }, "JavaScript-Mode.xshd"); hlm.RegisterHighlighting("HTML", new[] { ".htm", ".html" }, "HTML-Mode.xshd"); hlm.RegisterHighlighting("ASP/XHTML", new[] { ".asp", ".aspx", ".asax", ".asmx", ".ascx", ".master" }, "ASPX.xshd"); hlm.RegisterHighlighting("Boo", new[] { ".boo" }, "Boo.xshd"); hlm.RegisterHighlighting("Coco", new[] { ".atg" }, "Coco-Mode.xshd"); hlm.RegisterHighlighting("CSS", new[] { ".css" }, "CSS-Mode.xshd"); hlm.RegisterHighlighting("C++", new[] { ".c", ".h", ".cc", ".cpp", ".hpp" }, "CPP-Mode.xshd"); hlm.RegisterHighlighting("Java", new[] { ".java" }, "Java-Mode.xshd"); hlm.RegisterHighlighting("Patch", new[] { ".patch", ".diff" }, "Patch-Mode.xshd"); hlm.RegisterHighlighting("PowerShell", new[] { ".ps1", ".psm1", ".psd1" }, "PowerShell.xshd"); hlm.RegisterHighlighting("PHP", new[] { ".php" }, "PHP-Mode.xshd"); hlm.RegisterHighlighting("Python", new[] { ".py", ".pyw" }, "Python-Mode.xshd"); hlm.RegisterHighlighting("TeX", new[] { ".tex" }, "Tex-Mode.xshd"); hlm.RegisterHighlighting("TSQL", new[] { ".sql" }, "TSQL-Mode.xshd"); hlm.RegisterHighlighting("VB", new[] { ".vb" }, "VB-Mode.xshd"); ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } } hlm.RegisterHighlighting("Json", new[] { ".json" }, "Json.xshd"); } } } <MSG> fix xaml highlighting support <DFF> @@ -58,7 +58,7 @@ namespace AvaloniaEdit.Highlighting ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); - hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); + hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-Mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } }
1
fix xaml highlighting support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068063
<NME> Resources.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.IO; using System.Reflection; // ReSharper disable once CheckNamespace namespace AvaloniaEdit.Highlighting { internal static class Resources { private const string Prefix = "AvaloniaEdit.Highlighting.Resources."; public static Stream OpenStream(string name) { var s = typeof(Resources).GetTypeInfo().Assembly.GetManifestResourceStream(Prefix + name); if (s == null) throw new FileNotFoundException("The resource file '" + name + "' was not found."); return s; } internal static void RegisterBuiltInHighlightings(HighlightingManager.DefaultHighlightingManager hlm) { hlm.RegisterHighlighting("XmlDoc", null, "XmlDoc.xshd"); hlm.RegisterHighlighting("C#", new[] { ".cs" }, "CSharp-Mode.xshd"); hlm.RegisterHighlighting("JavaScript", new[] { ".js" }, "JavaScript-Mode.xshd"); hlm.RegisterHighlighting("HTML", new[] { ".htm", ".html" }, "HTML-Mode.xshd"); hlm.RegisterHighlighting("ASP/XHTML", new[] { ".asp", ".aspx", ".asax", ".asmx", ".ascx", ".master" }, "ASPX.xshd"); hlm.RegisterHighlighting("Boo", new[] { ".boo" }, "Boo.xshd"); hlm.RegisterHighlighting("Coco", new[] { ".atg" }, "Coco-Mode.xshd"); hlm.RegisterHighlighting("CSS", new[] { ".css" }, "CSS-Mode.xshd"); hlm.RegisterHighlighting("C++", new[] { ".c", ".h", ".cc", ".cpp", ".hpp" }, "CPP-Mode.xshd"); hlm.RegisterHighlighting("Java", new[] { ".java" }, "Java-Mode.xshd"); hlm.RegisterHighlighting("Patch", new[] { ".patch", ".diff" }, "Patch-Mode.xshd"); hlm.RegisterHighlighting("PowerShell", new[] { ".ps1", ".psm1", ".psd1" }, "PowerShell.xshd"); hlm.RegisterHighlighting("PHP", new[] { ".php" }, "PHP-Mode.xshd"); hlm.RegisterHighlighting("Python", new[] { ".py", ".pyw" }, "Python-Mode.xshd"); hlm.RegisterHighlighting("TeX", new[] { ".tex" }, "Tex-Mode.xshd"); hlm.RegisterHighlighting("TSQL", new[] { ".sql" }, "TSQL-Mode.xshd"); hlm.RegisterHighlighting("VB", new[] { ".vb" }, "VB-Mode.xshd"); ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } } hlm.RegisterHighlighting("Json", new[] { ".json" }, "Json.xshd"); } } } <MSG> fix xaml highlighting support <DFF> @@ -58,7 +58,7 @@ namespace AvaloniaEdit.Highlighting ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); - hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); + hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-Mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } }
1
fix xaml highlighting support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068064
<NME> Resources.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.IO; using System.Reflection; // ReSharper disable once CheckNamespace namespace AvaloniaEdit.Highlighting { internal static class Resources { private const string Prefix = "AvaloniaEdit.Highlighting.Resources."; public static Stream OpenStream(string name) { var s = typeof(Resources).GetTypeInfo().Assembly.GetManifestResourceStream(Prefix + name); if (s == null) throw new FileNotFoundException("The resource file '" + name + "' was not found."); return s; } internal static void RegisterBuiltInHighlightings(HighlightingManager.DefaultHighlightingManager hlm) { hlm.RegisterHighlighting("XmlDoc", null, "XmlDoc.xshd"); hlm.RegisterHighlighting("C#", new[] { ".cs" }, "CSharp-Mode.xshd"); hlm.RegisterHighlighting("JavaScript", new[] { ".js" }, "JavaScript-Mode.xshd"); hlm.RegisterHighlighting("HTML", new[] { ".htm", ".html" }, "HTML-Mode.xshd"); hlm.RegisterHighlighting("ASP/XHTML", new[] { ".asp", ".aspx", ".asax", ".asmx", ".ascx", ".master" }, "ASPX.xshd"); hlm.RegisterHighlighting("Boo", new[] { ".boo" }, "Boo.xshd"); hlm.RegisterHighlighting("Coco", new[] { ".atg" }, "Coco-Mode.xshd"); hlm.RegisterHighlighting("CSS", new[] { ".css" }, "CSS-Mode.xshd"); hlm.RegisterHighlighting("C++", new[] { ".c", ".h", ".cc", ".cpp", ".hpp" }, "CPP-Mode.xshd"); hlm.RegisterHighlighting("Java", new[] { ".java" }, "Java-Mode.xshd"); hlm.RegisterHighlighting("Patch", new[] { ".patch", ".diff" }, "Patch-Mode.xshd"); hlm.RegisterHighlighting("PowerShell", new[] { ".ps1", ".psm1", ".psd1" }, "PowerShell.xshd"); hlm.RegisterHighlighting("PHP", new[] { ".php" }, "PHP-Mode.xshd"); hlm.RegisterHighlighting("Python", new[] { ".py", ".pyw" }, "Python-Mode.xshd"); hlm.RegisterHighlighting("TeX", new[] { ".tex" }, "Tex-Mode.xshd"); hlm.RegisterHighlighting("TSQL", new[] { ".sql" }, "TSQL-Mode.xshd"); hlm.RegisterHighlighting("VB", new[] { ".vb" }, "VB-Mode.xshd"); ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } } hlm.RegisterHighlighting("Json", new[] { ".json" }, "Json.xshd"); } } } <MSG> fix xaml highlighting support <DFF> @@ -58,7 +58,7 @@ namespace AvaloniaEdit.Highlighting ".booproj;.build;.xfrm;.targets;.xaml;.xpt;" + ".xft;.map;.wsdl;.disco;.ps1xml;.nuspec").Split(';'), "XML-Mode.xshd"); - hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-mode.xshd"); + hlm.RegisterHighlighting("XAML", new[] { ".xaml", ".paml" }, "XML-Mode.xshd"); hlm.RegisterHighlighting("MarkDown", new[] { ".md" }, "MarkDown-Mode.xshd"); } }
1
fix xaml highlighting support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068065
<NME> injection.md <BEF> ## DOM injection Once you have [assembled](assembling-views.md) and [rendered](rendering-views.md) your View you'll want to inject it into the DOM at some point. *FruitMachine* has two ways of doing this: - `.inject(<Element>)` Empties the contents of the given element, then appends `view.el`. - `.appendTo(<Element>)` Appends `view.el` to the given Element. - `.insertBefore(<Element>, <Element>)` Appends `view.el` to the given Element as a previous sibling of the second Element parameter. ### `View#inject()` ```js var container = document.querySelector('.container'); var apple = new Apple(); apple.render(); apple.inject(container); ``` ### `View#appendTo()` ```js var list = document.querySelector('.list'); var apple = new Apple(); apple.render(); apple.appendTo(list); ``` <MSG> Merge pull request #68 from ftlabs/fix-docs Fixed links <DFF> @@ -1,6 +1,6 @@ ## DOM injection -Once you have [assembled](assembling-views.md) and [rendered](rendering-views.md) your View you'll want to inject it into the DOM at some point. *FruitMachine* has two ways of doing this: +Once you have [assembled](layout-assembly.md) and [rendered](rendering.md) your View you'll want to inject it into the DOM at some point. *FruitMachine* has two ways of doing this: - `.inject(<Element>)` Empties the contents of the given element, then appends `view.el`. - `.appendTo(<Element>)` Appends `view.el` to the given Element.
1
Merge pull request #68 from ftlabs/fix-docs
1
.md
md
mit
ftlabs/fruitmachine
10068066
<NME> jsgrid.core.js <BEF> (function(window, $, undefined) { var JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID, JSGRID_ROW_DATA_KEY = "JSGridItem", JSGRID_EDIT_ROW_DATA_KEY = "JSGridEditRow", SORT_ORDER_ASC = "asc", SORT_ORDER_DESC = "desc", FIRST_PAGE_PLACEHOLDER = "{first}", PAGES_PLACEHOLDER = "{pages}", PREV_PAGE_PLACEHOLDER = "{prev}", NEXT_PAGE_PLACEHOLDER = "{next}", LAST_PAGE_PLACEHOLDER = "{last}", PAGE_INDEX_PLACEHOLDER = "{pageIndex}", PAGE_COUNT_PLACEHOLDER = "{pageCount}", ITEM_COUNT_PLACEHOLDER = "{itemCount}", EMPTY_HREF = "javascript:void(0);"; var getOrApply = function(value, context) { if($.isFunction(value)) { return value.apply(context, $.makeArray(arguments).slice(2)); } return value; }; var normalizePromise = function(promise) { var d = $.Deferred(); if(promise && promise.then) { promise.then(function() { d.resolve.apply(d, arguments); }, function() { d.reject.apply(d, arguments); }); } else { d.resolve(promise); } return d.promise(); }; var defaultController = { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }; function Grid(element, config) { var $element = $(element); $element.data(JSGRID_DATA_KEY, this); this._container = $element; this.data = []; this.fields = []; this._editingRow = null; this._sortField = null; this._sortOrder = SORT_ORDER_ASC; this._firstDisplayingPage = 1; this._init(config); this.render(); } Grid.prototype = { width: "auto", height: "auto", updateOnResize: true, rowClass: $.noop, rowRenderer: null, rowClick: function(args) { if(this.editing) { this.editItem($(args.event.target).closest("tr")); } }, rowDoubleClick: $.noop, noDataContent: "Not found", noDataRowClass: "jsgrid-nodata-row", heading: true, headerRowRenderer: null, headerRowClass: "jsgrid-header-row", headerCellClass: "jsgrid-header-cell", filtering: false, filterRowRenderer: null, filterRowClass: "jsgrid-filter-row", inserting: false, insertRowLocation: "bottom", insertRowRenderer: null, insertRowClass: "jsgrid-insert-row", editing: false, editRowRenderer: null, editRowClass: "jsgrid-edit-row", confirmDeleting: true, deleteConfirm: "Are you sure?", selecting: true, selectedRowClass: "jsgrid-selected-row", oddRowClass: "jsgrid-row", evenRowClass: "jsgrid-alt-row", cellClass: "jsgrid-cell", sorting: false, sortableClass: "jsgrid-header-sortable", sortAscClass: "jsgrid-header-sort jsgrid-header-sort-asc", sortDescClass: "jsgrid-header-sort jsgrid-header-sort-desc", paging: false, pagerContainer: null, pageIndex: 1, pageSize: 20, pageButtonCount: 15, pagerFormat: "Pages: {first} {prev} {pages} {next} {last} &nbsp;&nbsp; {pageIndex} of {pageCount}", pagePrevText: "Prev", pageNextText: "Next", pageFirstText: "First", pageLastText: "Last", pageNavigatorNextText: "...", pageNavigatorPrevText: "...", pagerContainerClass: "jsgrid-pager-container", pagerClass: "jsgrid-pager", pagerNavButtonClass: "jsgrid-pager-nav-button", pagerNavButtonInactiveClass: "jsgrid-pager-nav-inactive-button", pageClass: "jsgrid-pager-page", currentPageClass: "jsgrid-pager-current-page", customLoading: false, pageLoading: false, autoload: false, controller: defaultController, loadIndication: true, loadIndicationDelay: 500, loadMessage: "Please, wait...", loadShading: true, invalidMessage: "Invalid data entered!", invalidNotify: function(args) { var messages = $.map(args.errors, function(error) { return error.message || null; }); window.alert([this.invalidMessage].concat(messages).join("\n")); }, onInit: $.noop, onRefreshing: $.noop, onRefreshed: $.noop, onPageChanged: $.noop, onItemDeleting: $.noop, onItemDeleted: $.noop, onItemInserting: $.noop, onItemInserted: $.noop, onItemEditing: $.noop, onItemEditCancelling: $.noop, onItemUpdating: $.noop, onItemUpdated: $.noop, onItemInvalid: $.noop, onDataLoading: $.noop, onDataLoaded: $.noop, onDataExporting: $.noop, onOptionChanging: $.noop, onOptionChanged: $.noop, onError: $.noop, invalidClass: "jsgrid-invalid", containerClass: "jsgrid", tableClass: "jsgrid-table", gridHeaderClass: "jsgrid-grid-header", gridBodyClass: "jsgrid-grid-body", _init: function(config) { $.extend(this, config); this._initLoadStrategy(); this._initController(); this._initFields(); this._attachWindowLoadResize(); this._attachWindowResizeCallback(); this._callEventHandler(this.onInit) }, loadStrategy: function() { return this.pageLoading ? new jsGrid.loadStrategies.PageLoadingStrategy(this) : new jsGrid.loadStrategies.DirectLoadingStrategy(this); }, _initLoadStrategy: function() { this._loadStrategy = getOrApply(this.loadStrategy, this); }, _initController: function() { this._controller = $.extend({}, defaultController, getOrApply(this.controller, this)); }, renderTemplate: function(source, context, config) { var args = []; for(var key in config) { args.push(config[key]); } args.unshift(source, context); source = getOrApply.apply(null, args); return (source === undefined || source === null) ? "" : source; }, loadIndicator: function(config) { return new jsGrid.LoadIndicator(config); }, validation: function(config) { return jsGrid.Validation && new jsGrid.Validation(config); }, _initFields: function() { var self = this; self.fields = $.map(self.fields, function(field) { if($.isPlainObject(field)) { var fieldConstructor = (field.type && jsGrid.fields[field.type]) || jsGrid.Field; field = new fieldConstructor(field); } field._grid = self; return field; }); }, _attachWindowLoadResize: function() { $(window).on("load", $.proxy(this._refreshSize, this)); }, _attachWindowResizeCallback: function() { if(this.updateOnResize) { $(window).on("resize", $.proxy(this._refreshSize, this)); } }, _detachWindowResizeCallback: function() { $(window).off("resize", this._refreshSize); }, option: function(key, value) { var optionChangingEventArgs, optionChangedEventArgs; if(arguments.length === 1) return this[key]; optionChangingEventArgs = { option: key, oldValue: this[key], newValue: value }; this._callEventHandler(this.onOptionChanging, optionChangingEventArgs); this._handleOptionChange(optionChangingEventArgs.option, optionChangingEventArgs.newValue); optionChangedEventArgs = { option: optionChangingEventArgs.option, value: optionChangingEventArgs.newValue }; this._callEventHandler(this.onOptionChanged, optionChangedEventArgs); }, fieldOption: function(field, key, value) { field = this._normalizeField(field); if(arguments.length === 2) return field[key]; field[key] = value; this._renderGrid(); }, _handleOptionChange: function(name, value) { this[name] = value; switch(name) { case "width": case "height": this._refreshSize(); break; case "rowClass": case "rowRenderer": case "rowClick": case "rowDoubleClick": case "noDataRowClass": case "noDataContent": case "selecting": case "selectedRowClass": case "oddRowClass": case "evenRowClass": this._refreshContent(); break; case "pageButtonCount": case "pagerFormat": case "pagePrevText": case "pageNextText": case "pageFirstText": case "pageLastText": case "pageNavigatorNextText": case "pageNavigatorPrevText": case "pagerClass": case "pagerNavButtonClass": case "pageClass": case "currentPageClass": case "pagerRenderer": this._refreshPager(); break; case "fields": this._initFields(); this.render(); break; case "data": case "editing": case "heading": case "filtering": case "inserting": case "paging": this.refresh(); break; case "loadStrategy": case "pageLoading": this._initLoadStrategy(); this.search(); break; case "pageIndex": this.openPage(value); break; case "pageSize": this.refresh(); this.search(); break; case "editRowRenderer": case "editRowClass": this.cancelEdit(); break; case "updateOnResize": this._detachWindowResizeCallback(); this._attachWindowResizeCallback(); break; case "invalidNotify": case "invalidMessage": break; default: this.render(); break; } }, destroy: function() { this._detachWindowResizeCallback(); this._clear(); this._container.removeData(JSGRID_DATA_KEY); }, render: function() { this._renderGrid(); return this.autoload ? this.loadData() : $.Deferred().resolve().promise(); }, _renderGrid: function() { this._clear(); this._container.addClass(this.containerClass) .css("position", "relative") .append(this._createHeader()) .append(this._createBody()); this._pagerContainer = this._createPagerContainer(); this._loadIndicator = this._createLoadIndicator(); this._validation = this._createValidation(); this.refresh(); }, _createLoadIndicator: function() { return getOrApply(this.loadIndicator, this, { message: this.loadMessage, shading: this.loadShading, container: this._container }); }, _createValidation: function() { return getOrApply(this.validation, this); }, _clear: function() { this.cancelEdit(); clearTimeout(this._loadingTimer); this._pagerContainer && this._pagerContainer.empty(); this._container.empty() .css({ position: "", width: "", height: "" }); }, _createHeader: function() { var $headerRow = this._headerRow = this._createHeaderRow(), $filterRow = this._filterRow = this._createFilterRow(), $insertRow = this._insertRow = this._createInsertRow(); var $headerGrid = this._headerGrid = $("<table>").addClass(this.tableClass) .append($headerRow) .append($filterRow) .append($insertRow); var $header = this._header = $("<div>").addClass(this.gridHeaderClass) .addClass(this._scrollBarWidth() ? "jsgrid-header-scrollbar" : "") .append($headerGrid); return $header; }, _createBody: function() { var $content = this._content = $("<tbody>"); var $bodyGrid = this._bodyGrid = $("<table>").addClass(this.tableClass) .append($content); var $body = this._body = $("<div>").addClass(this.gridBodyClass) .append($bodyGrid) .on("scroll", $.proxy(function(e) { this._header.scrollLeft(e.target.scrollLeft); }, this)); return $body; }, _createPagerContainer: function() { var pagerContainer = this.pagerContainer || $("<div>").appendTo(this._container); return $(pagerContainer).addClass(this.pagerContainerClass); }, _eachField: function(callBack) { var self = this; $.each(this.fields, function(index, field) { if(field.visible) { callBack.call(self, field, index); } }); }, _createHeaderRow: function() { if($.isFunction(this.headerRowRenderer)) return $(this.renderTemplate(this.headerRowRenderer, this)); var $result = $("<tr>").addClass(this.headerRowClass); this._eachField(function(field, index) { var $th = this._prepareCell("<th>", field, "headercss", this.headerCellClass) .append(this.renderTemplate(field.headerTemplate, field)) .appendTo($result); if(this.sorting && field.sorting) { $th.addClass(this.sortableClass) .on("click", $.proxy(function() { this.sort(index); }, this)); } }); return $result; }, _prepareCell: function(cell, field, cssprop, cellClass) { return $(cell).css("width", field.width) .addClass(cellClass || this.cellClass) .addClass((cssprop && field[cssprop]) || field.css) .addClass(field.align ? ("jsgrid-align-" + field.align) : ""); }, _createFilterRow: function() { if($.isFunction(this.filterRowRenderer)) return $(this.renderTemplate(this.filterRowRenderer, this)); var $result = $("<tr>").addClass(this.filterRowClass); this._eachField(function(field) { this._prepareCell("<td>", field, "filtercss") .append(this.renderTemplate(field.filterTemplate, field)) .appendTo($result); }); return $result; }, _createInsertRow: function() { if($.isFunction(this.insertRowRenderer)) return $(this.renderTemplate(this.insertRowRenderer, this)); var $result = $("<tr>").addClass(this.insertRowClass); this._eachField(function(field) { this._prepareCell("<td>", field, "insertcss") .append(this.renderTemplate(field.insertTemplate, field)) .appendTo($result); }); return $result; }, _callEventHandler: function(handler, eventParams) { handler.call(this, $.extend(eventParams, { grid: this })); return eventParams; }, reset: function() { this._resetSorting(); this._resetPager(); return this._loadStrategy.reset(); }, _resetPager: function() { this._firstDisplayingPage = 1; this._setPage(1); }, _resetSorting: function() { this._sortField = null; this._sortOrder = SORT_ORDER_ASC; this._clearSortingCss(); }, refresh: function() { this._callEventHandler(this.onRefreshing); this.cancelEdit(); this._refreshHeading(); this._refreshFiltering(); this._refreshInserting(); this._refreshContent(); this._refreshPager(); this._refreshSize(); this._callEventHandler(this.onRefreshed); }, _refreshHeading: function() { this._headerRow.toggle(this.heading); }, _refreshFiltering: function() { this._filterRow.toggle(this.filtering); }, _refreshInserting: function() { this._insertRow.toggle(this.inserting); }, _refreshContent: function() { var $content = this._content; $content.empty(); if(!this.data.length) { $content.append(this._createNoDataRow()); return this; } var indexFrom = this._loadStrategy.firstDisplayIndex(); var indexTo = this._loadStrategy.lastDisplayIndex(); for(var itemIndex = indexFrom; itemIndex < indexTo; itemIndex++) { var item = this.data[itemIndex]; $content.append(this._createRow(item, itemIndex)); } }, _createNoDataRow: function() { var amountOfFields = 0; this._eachField(function() { amountOfFields++; }); return $("<tr>").addClass(this.noDataRowClass) .append($("<td>").addClass(this.cellClass).attr("colspan", amountOfFields) .append(this.renderTemplate(this.noDataContent, this))); }, _createRow: function(item, itemIndex) { var $result; if($.isFunction(this.rowRenderer)) { $result = this.renderTemplate(this.rowRenderer, this, { item: item, itemIndex: itemIndex }); } else { $result = $("<tr>"); this._renderCells($result, item); } $result.addClass(this._getRowClasses(item, itemIndex)) .data(JSGRID_ROW_DATA_KEY, item) .on("click", $.proxy(function(e) { $result = $("<td>").append(field.itemTemplate ? field.itemTemplate(fieldValue, item) : fieldValue); } $result.addClass(field.css) .width(field.width); field.align && $result.addClass("jsgrid-align-" + field.align); itemIndex: itemIndex, event: e }); }, this)); if(this.selecting) { this._attachRowHover($result); } return $result; }, _getRowClasses: function(item, itemIndex) { var classes = []; classes.push(((itemIndex + 1) % 2) ? this.oddRowClass : this.evenRowClass); classes.push(getOrApply(this.rowClass, this, item, itemIndex)); return classes.join(" "); }, _attachRowHover: function($row) { var selectedRowClass = this.selectedRowClass; $row.hover(function() { $(this).addClass(selectedRowClass); }, function() { $(this).removeClass(selectedRowClass); } ); }, _renderCells: function($row, item) { this._eachField(function(field) { $row.append(this._createCell(item, field)); }); return this; }, _createCell: function(item, field) { var $result; var fieldValue = this._getItemFieldValue(item, field); var args = { value: fieldValue, item : item }; if($.isFunction(field.cellRenderer)) { $result = this.renderTemplate(field.cellRenderer, field, args); } else { $result = $("<td>").append(this.renderTemplate(field.itemTemplate || fieldValue, field, args)); } return this._prepareCell($result, field); }, _getItemFieldValue: function(item, field) { var props = field.name.split('.'); var result = item[props.shift()]; while(result && props.length) { result = result[props.shift()]; } return result; }, _setItemFieldValue: function(item, field, value) { var props = field.name.split('.'); var current = item; var prop = props[0]; while(current && props.length) { item = current; prop = props.shift(); current = item[prop]; } if(!current) { while(props.length) { item = item[prop] = {}; prop = props.shift(); } } item[prop] = value; }, sort: function(field, order) { if($.isPlainObject(field)) { order = field.order; field = field.field; } this._clearSortingCss(); this._setSortingParams(field, order); this._setSortingCss(); return this._loadStrategy.sort(); }, _clearSortingCss: function() { this._headerRow.find("th") .removeClass(this.sortAscClass) .removeClass(this.sortDescClass); }, _setSortingParams: function(field, order) { field = this._normalizeField(field); order = order || ((this._sortField === field) ? this._reversedSortOrder(this._sortOrder) : SORT_ORDER_ASC); this._sortField = field; this._sortOrder = order; }, _normalizeField: function(field) { if($.isNumeric(field)) { return this.fields[field]; } if(typeof field === "string") { return $.grep(this.fields, function(f) { return f.name === field; })[0]; } return field; }, _reversedSortOrder: function(order) { return (order === SORT_ORDER_ASC ? SORT_ORDER_DESC : SORT_ORDER_ASC); }, _setSortingCss: function() { var fieldIndex = this._visibleFieldIndex(this._sortField); this._headerRow.find("th").eq(fieldIndex) .addClass(this._sortOrder === SORT_ORDER_ASC ? this.sortAscClass : this.sortDescClass); }, _visibleFieldIndex: function(field) { return $.inArray(field, $.grep(this.fields, function(f) { return f.visible; })); }, _sortData: function() { var sortFactor = this._sortFactor(), sortField = this._sortField; if(sortField) { var self = this; self.data.sort(function(item1, item2) { var value1 = self._getItemFieldValue(item1, sortField); var value2 = self._getItemFieldValue(item2, sortField); return sortFactor * sortField.sortingFunc(value1, value2); }); } }, _sortFactor: function() { return this._sortOrder === SORT_ORDER_ASC ? 1 : -1; }, _itemsCount: function() { return this._loadStrategy.itemsCount(); }, _pagesCount: function() { var itemsCount = this._itemsCount(), pageSize = this.pageSize; return Math.floor(itemsCount / pageSize) + (itemsCount % pageSize ? 1 : 0); }, _refreshPager: function() { var $pagerContainer = this._pagerContainer; $pagerContainer.empty(); if(this.paging) { $pagerContainer.append(this._createPager()); } var showPager = this.paging && this._pagesCount() > 1; $pagerContainer.toggle(showPager); }, _createPager: function() { var $result; if($.isFunction(this.pagerRenderer)) { $result = $(this.pagerRenderer({ pageIndex: this.pageIndex, pageCount: this._pagesCount() })); } else { $result = $("<div>").append(this._createPagerByFormat()); } $result.addClass(this.pagerClass); return $result; }, _createPagerByFormat: function() { var pageIndex = this.pageIndex, pageCount = this._pagesCount(), itemCount = this._itemsCount(), pagerParts = this.pagerFormat.split(" "); return $.map(pagerParts, $.proxy(function(pagerPart) { var result = pagerPart; if(pagerPart === PAGES_PLACEHOLDER) { result = this._createPages(); } else if(pagerPart === FIRST_PAGE_PLACEHOLDER) { result = this._createPagerNavButton(this.pageFirstText, 1, pageIndex > 1); } else if(pagerPart === PREV_PAGE_PLACEHOLDER) { result = this._createPagerNavButton(this.pagePrevText, pageIndex - 1, pageIndex > 1); } else if(pagerPart === NEXT_PAGE_PLACEHOLDER) { result = this._createPagerNavButton(this.pageNextText, pageIndex + 1, pageIndex < pageCount); } else if(pagerPart === LAST_PAGE_PLACEHOLDER) { result = this._createPagerNavButton(this.pageLastText, pageCount, pageIndex < pageCount); } else if(pagerPart === PAGE_INDEX_PLACEHOLDER) { result = pageIndex; } else if(pagerPart === PAGE_COUNT_PLACEHOLDER) { result = pageCount; } else if(pagerPart === ITEM_COUNT_PLACEHOLDER) { result = itemCount; } return $.isArray(result) ? result.concat([" "]) : [result, " "]; }, this)); }, _createPages: function() { var pageCount = this._pagesCount(), pageButtonCount = this.pageButtonCount, firstDisplayingPage = this._firstDisplayingPage, pages = []; if(firstDisplayingPage > 1) { pages.push(this._createPagerPageNavButton(this.pageNavigatorPrevText, this.showPrevPages)); } for(var i = 0, pageNumber = firstDisplayingPage; i < pageButtonCount && pageNumber <= pageCount; i++, pageNumber++) { pages.push(pageNumber === this.pageIndex ? this._createPagerCurrentPage() : this._createPagerPage(pageNumber)); } if((firstDisplayingPage + pageButtonCount - 1) < pageCount) { pages.push(this._createPagerPageNavButton(this.pageNavigatorNextText, this.showNextPages)); } return pages; }, _createPagerNavButton: function(text, pageIndex, isActive) { return this._createPagerButton(text, this.pagerNavButtonClass + (isActive ? "" : " " + this.pagerNavButtonInactiveClass), isActive ? function() { this.openPage(pageIndex); } : $.noop); }, _createPagerPageNavButton: function(text, handler) { return this._createPagerButton(text, this.pagerNavButtonClass, handler); }, _createPagerPage: function(pageIndex) { return this._createPagerButton(pageIndex, this.pageClass, function() { this.openPage(pageIndex); }); }, _createPagerButton: function(text, css, handler) { var $link = $("<a>").attr("href", EMPTY_HREF) .html(text) .on("click", $.proxy(handler, this)); return $("<span>").addClass(css).append($link); }, _createPagerCurrentPage: function() { return $("<span>") .addClass(this.pageClass) .addClass(this.currentPageClass) .text(this.pageIndex); }, _refreshSize: function() { this._refreshHeight(); this._refreshWidth(); }, _refreshWidth: function() { var width = (this.width === "auto") ? this._getAutoWidth() : this.width; this._container.width(width); }, _getAutoWidth: function() { var $headerGrid = this._headerGrid, $header = this._header; $headerGrid.width("auto"); var contentWidth = $headerGrid.outerWidth(); var borderWidth = $header.outerWidth() - $header.innerWidth(); $headerGrid.width(""); return contentWidth + borderWidth; }, _scrollBarWidth: (function() { var result; return function() { if(result === undefined) { var $ghostContainer = $("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>"); var $ghostContent = $("<div style='height:100px;'></div>"); $ghostContainer.append($ghostContent).appendTo("body"); var width = $ghostContent.innerWidth(); $ghostContainer.css("overflow-y", "auto"); var widthExcludingScrollBar = $ghostContent.innerWidth(); $ghostContainer.remove(); result = width - widthExcludingScrollBar; } return result; }; })(), _refreshHeight: function() { var container = this._container, pagerContainer = this._pagerContainer, height = this.height, nonBodyHeight; container.height(height); if(height !== "auto") { height = container.height(); nonBodyHeight = this._header.outerHeight(true); if(pagerContainer.parents(container).length) { nonBodyHeight += pagerContainer.outerHeight(true); } this._body.outerHeight(height - nonBodyHeight); } }, showPrevPages: function() { var firstDisplayingPage = this._firstDisplayingPage, pageButtonCount = this.pageButtonCount; this._firstDisplayingPage = (firstDisplayingPage > pageButtonCount) ? firstDisplayingPage - pageButtonCount : 1; this._refreshPager(); }, showNextPages: function() { var firstDisplayingPage = this._firstDisplayingPage, pageButtonCount = this.pageButtonCount, pageCount = this._pagesCount(); this._firstDisplayingPage = (firstDisplayingPage + 2 * pageButtonCount > pageCount) ? pageCount - pageButtonCount + 1 : firstDisplayingPage + pageButtonCount; this._refreshPager(); }, openPage: function(pageIndex) { if(pageIndex < 1 || pageIndex > this._pagesCount()) return; this._setPage(pageIndex); this._loadStrategy.openPage(pageIndex); }, _setPage: function(pageIndex) { var firstDisplayingPage = this._firstDisplayingPage, pageButtonCount = this.pageButtonCount; this.pageIndex = pageIndex; if(pageIndex < firstDisplayingPage) { this._firstDisplayingPage = pageIndex; } if(pageIndex > firstDisplayingPage + pageButtonCount - 1) { this._firstDisplayingPage = pageIndex - pageButtonCount + 1; } this._callEventHandler(this.onPageChanged, { pageIndex: pageIndex }); }, _controllerCall: function(method, param, isCanceled, doneCallback) { if(isCanceled) return $.Deferred().reject().promise(); this._showLoading(); var controller = this._controller; if(!controller || !controller[method]) { throw Error("controller has no method '" + method + "'"); } return normalizePromise(controller[method](param)) .done($.proxy(doneCallback, this)) .fail($.proxy(this._errorHandler, this)) .always($.proxy(this._hideLoading, this)); }, _errorHandler: function() { this._callEventHandler(this.onError, { args: $.makeArray(arguments) }); }, _showLoading: function() { if(!this.loadIndication) return; clearTimeout(this._loadingTimer); this._loadingTimer = setTimeout($.proxy(function() { this._loadIndicator.show(); }, this), this.loadIndicationDelay); }, _hideLoading: function() { if(!this.loadIndication) return; clearTimeout(this._loadingTimer); this._loadIndicator.hide(); }, search: function(filter) { this._resetSorting(); this._resetPager(); return this.loadData(filter); }, loadData: function(filter) { filter = filter || (this.filtering ? this.getFilter() : {}); $.extend(filter, this._loadStrategy.loadParams(), this._sortingParams()); var args = this._callEventHandler(this.onDataLoading, { filter: filter }); return this._controllerCall("loadData", filter, args.cancel, function(loadedData) { if(!loadedData) return; this._loadStrategy.finishLoad(loadedData); this._callEventHandler(this.onDataLoaded, { data: loadedData }); }); }, exportData: function(exportOptions){ var options = exportOptions || {}; var type = options.type || "csv"; var result = ""; this._callEventHandler(this.onDataExporting); switch(type){ case "csv": result = this._dataToCsv(options); break; } return result; }, _dataToCsv: function(options){ var options = options || {}; var includeHeaders = options.hasOwnProperty("includeHeaders") ? options.includeHeaders : true; var subset = options.subset || "all"; var filter = options.filter || undefined; var result = []; if (includeHeaders){ var fieldsLength = this.fields.length; var fieldNames = {}; for(var i=0;i<fieldsLength;i++){ var field = this.fields[i]; if ("includeInDataExport" in field){ if (field.includeInDataExport === true) fieldNames[i] = field.title || field.name; } } var headerLine = this._itemToCsv(fieldNames,{},options); result.push(headerLine); } var exportStartIndex = 0; var exportEndIndex = this.data.length; switch(subset){ case "visible": exportEndIndex = this._firstDisplayingPage * this.pageSize; exportStartIndex = exportEndIndex - this.pageSize; case "all": default: break; } for (var i = exportStartIndex; i < exportEndIndex; i++){ var item = this.data[i]; var itemLine = ""; var includeItem = true; if (filter) if (!filter(item)) includeItem = false; if (includeItem){ itemLine = this._itemToCsv(item, this.fields, options); result.push(itemLine); } } return result.join(""); }, _itemToCsv: function(item, fields, options){ var options = options || {}; var delimiter = options.delimiter || "|"; var encapsulate = options.hasOwnProperty("encapsulate") ? options.encapsulate : true; var newline = options.newline || "\r\n"; var transforms = options.transforms || {}; var fields = fields || {}; var getItem = this._getItemFieldValue; var result = []; Object.keys(item).forEach(function(key,index) { var entry = ""; //Fields.length is greater than 0 when we are matching agaisnt fields //Field.length will be 0 when exporting header rows if (fields.length > 0){ var field = fields[index]; //Field may be excluded from data export if ("includeInDataExport" in field){ if (field.includeInDataExport){ //Field may be a select, which requires additional logic if (field.type === "select"){ var selectedItem = getItem(item, field); var resultItem = $.grep(field.items, function(item, index) { return item[field.valueField] === selectedItem; })[0] || ""; entry = resultItem[field.textField]; } else{ entry = getItem(item, field); } } else{ return; } } else{ entry = getItem(item, field); } if (transforms.hasOwnProperty(field.name)){ entry = transforms[field.name](entry); } } else{ entry = item[key]; } if (encapsulate){ entry = '"'+entry+'"'; } result.push(entry); }); return result.join(delimiter) + newline; }, getFilter: function() { var result = {}; this._eachField(function(field) { if(field.filtering) { this._setItemFieldValue(result, field, field.filterValue()); } }); return result; }, _sortingParams: function() { if(this.sorting && this._sortField) { return { sortField: this._sortField.name, sortOrder: this._sortOrder }; } return {}; }, getSorting: function() { var sortingParams = this._sortingParams(); return { field: sortingParams.sortField, order: sortingParams.sortOrder }; }, clearFilter: function() { var $filterRow = this._createFilterRow(); this._filterRow.replaceWith($filterRow); this._filterRow = $filterRow; return this.search(); }, insertItem: function(item) { var insertingItem = item || this._getValidatedInsertItem(); if(!insertingItem) return $.Deferred().reject().promise(); var args = this._callEventHandler(this.onItemInserting, { item: insertingItem }); return this._controllerCall("insertItem", insertingItem, args.cancel, function(insertedItem) { insertedItem = insertedItem || insertingItem; this._loadStrategy.finishInsert(insertedItem, this.insertRowLocation); this._callEventHandler(this.onItemInserted, { item: insertedItem }); }); }, _getValidatedInsertItem: function() { var item = this._getInsertItem(); return this._validateItem(item, this._insertRow) ? item : null; }, _getInsertItem: function() { var result = {}; this._eachField(function(field) { if(field.inserting) { this._setItemFieldValue(result, field, field.insertValue()); } }); return result; }, _validateItem: function(item, $row) { var validationErrors = []; var args = { item: item, itemIndex: this._rowIndex($row), row: $row }; this._eachField(function(field) { if(!field.validate || ($row === this._insertRow && !field.inserting) || ($row === this._getEditRow() && !field.editing)) return; var fieldValue = this._getItemFieldValue(item, field); var errors = this._validation.validate($.extend({ value: fieldValue, rules: field.validate }, args)); this._setCellValidity($row.children().eq(this._visibleFieldIndex(field)), errors); if(!errors.length) return; validationErrors.push.apply(validationErrors, $.map(errors, function(message) { return { field: field, message: message }; })); }); if(!validationErrors.length) return true; var invalidArgs = $.extend({ errors: validationErrors }, args); this._callEventHandler(this.onItemInvalid, invalidArgs); this.invalidNotify(invalidArgs); return false; }, _setCellValidity: function($cell, errors) { $cell .toggleClass(this.invalidClass, !!errors.length) .attr("title", errors.join("\n")); }, clearInsert: function() { var insertRow = this._createInsertRow(); this._insertRow.replaceWith(insertRow); this._insertRow = insertRow; this.refresh(); }, editItem: function(item) { var $row = this.rowByItem(item); if($row.length) { this._editRow($row); } }, rowByItem: function(item) { if(item.jquery || item.nodeType) return $(item); return this._content.find("tr").filter(function() { return $.data(this, JSGRID_ROW_DATA_KEY) === item; }); }, _editRow: function($row) { if(!this.editing) return; var item = $row.data(JSGRID_ROW_DATA_KEY); var args = this._callEventHandler(this.onItemEditing, { row: $row, item: item, itemIndex: this._itemIndex(item) }); if(args.cancel) return; if(this._editingRow) { this.cancelEdit(); } var $editRow = this._createEditRow(item); this._editingRow = $row; $row.hide(); $editRow.insertBefore($row); $row.data(JSGRID_EDIT_ROW_DATA_KEY, $editRow); }, _createEditRow: function(item) { if($.isFunction(this.editRowRenderer)) { return $(this.renderTemplate(this.editRowRenderer, this, { item: item, itemIndex: this._itemIndex(item) })); } var $result = $("<tr>").addClass(this.editRowClass); this._eachField(function(field) { var fieldValue = this._getItemFieldValue(item, field); this._prepareCell("<td>", field, "editcss") .append(this.renderTemplate(field.editTemplate || "", field, { value: fieldValue, item: item })) .appendTo($result); }); return $result; }, updateItem: function(item, editedItem) { if(arguments.length === 1) { editedItem = item; } var $row = item ? this.rowByItem(item) : this._editingRow; editedItem = editedItem || this._getValidatedEditedItem(); if(!editedItem) return; return this._updateRow($row, editedItem); }, _getValidatedEditedItem: function() { var item = this._getEditedItem(); return this._validateItem(item, this._getEditRow()) ? item : null; }, _updateRow: function($updatingRow, editedItem) { var updatingItem = $updatingRow.data(JSGRID_ROW_DATA_KEY), updatingItemIndex = this._itemIndex(updatingItem), updatedItem = $.extend(true, {}, updatingItem, editedItem); var args = this._callEventHandler(this.onItemUpdating, { row: $updatingRow, item: updatedItem, itemIndex: updatingItemIndex, previousItem: updatingItem }); return this._controllerCall("updateItem", updatedItem, args.cancel, function(loadedUpdatedItem) { var previousItem = $.extend(true, {}, updatingItem); updatedItem = loadedUpdatedItem || $.extend(true, updatingItem, editedItem); var $updatedRow = this._finishUpdate($updatingRow, updatedItem, updatingItemIndex); this._callEventHandler(this.onItemUpdated, { row: $updatedRow, item: updatedItem, itemIndex: updatingItemIndex, previousItem: previousItem }); }); }, _rowIndex: function(row) { return this._content.children().index($(row)); }, _itemIndex: function(item) { return $.inArray(item, this.data); }, _finishUpdate: function($updatingRow, updatedItem, updatedItemIndex) { this.cancelEdit(); this.data[updatedItemIndex] = updatedItem; var $updatedRow = this._createRow(updatedItem, updatedItemIndex); $updatingRow.replaceWith($updatedRow); return $updatedRow; }, _getEditedItem: function() { var result = {}; this._eachField(function(field) { if(field.editing) { this._setItemFieldValue(result, field, field.editValue()); } }); return result; }, cancelEdit: function() { if(!this._editingRow) return; var $row = this._editingRow, editingItem = $row.data(JSGRID_ROW_DATA_KEY), editingItemIndex = this._itemIndex(editingItem); this._callEventHandler(this.onItemEditCancelling, { row: $row, item: editingItem, itemIndex: editingItemIndex }); this._getEditRow().remove(); this._editingRow.show(); this._editingRow = null; }, _getEditRow: function() { return this._editingRow && this._editingRow.data(JSGRID_EDIT_ROW_DATA_KEY); }, deleteItem: function(item) { var $row = this.rowByItem(item); if(!$row.length) return; if(this.confirmDeleting && !window.confirm(getOrApply(this.deleteConfirm, this, $row.data(JSGRID_ROW_DATA_KEY)))) return; return this._deleteRow($row); }, _deleteRow: function($row) { var deletingItem = $row.data(JSGRID_ROW_DATA_KEY), deletingItemIndex = this._itemIndex(deletingItem); var args = this._callEventHandler(this.onItemDeleting, { row: $row, item: deletingItem, itemIndex: deletingItemIndex }); return this._controllerCall("deleteItem", deletingItem, args.cancel, function() { this._loadStrategy.finishDelete(deletingItem, deletingItemIndex); this._callEventHandler(this.onItemDeleted, { row: $row, item: deletingItem, itemIndex: deletingItemIndex }); }); } }; $.fn.jsGrid = function(config) { var args = $.makeArray(arguments), methodArgs = args.slice(1), result = this; this.each(function() { var $element = $(this), instance = $element.data(JSGRID_DATA_KEY), methodResult; if(instance) { if(typeof config === "string") { methodResult = instance[config].apply(instance, methodArgs); if(methodResult !== undefined && methodResult !== instance) { result = methodResult; return false; } } else { instance._detachWindowResizeCallback(); instance._init(config); instance.render(); } } else { new Grid($element, config); } }); return result; }; var fields = {}; var setDefaults = function(config) { var componentPrototype; if($.isPlainObject(config)) { componentPrototype = Grid.prototype; } else { componentPrototype = fields[config].prototype; config = arguments[1] || {}; } $.extend(componentPrototype, config); }; var locales = {}; var locale = function(lang) { var localeConfig = $.isPlainObject(lang) ? lang : locales[lang]; if(!localeConfig) throw Error("unknown locale " + lang); setLocale(jsGrid, localeConfig); }; var setLocale = function(obj, localeConfig) { $.each(localeConfig, function(field, value) { if($.isPlainObject(value)) { setLocale(obj[field] || obj[field[0].toUpperCase() + field.slice(1)], value); return; } if(obj.hasOwnProperty(field)) { obj[field] = value; } else { obj.prototype[field] = value; } }); }; window.jsGrid = { Grid: Grid, fields: fields, setDefaults: setDefaults, locales: locales, locale: locale, version: "@VERSION" }; }(window, jQuery)); <MSG> Merge pull request #140 from sockhead/master Fix: Firefox td width issue <DFF> @@ -616,8 +616,9 @@ $result = $("<td>").append(field.itemTemplate ? field.itemTemplate(fieldValue, item) : fieldValue); } - $result.addClass(field.css) - .width(field.width); + $result.addClass(field.css); + $result.css({"width": field.width}); + field.align && $result.addClass("jsgrid-align-" + field.align);
3
Merge pull request #140 from sockhead/master
2
.js
core
mit
tabalinas/jsgrid
10068067
<NME> jsgrid.core.js <BEF> (function(window, $, undefined) { var JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID, JSGRID_ROW_DATA_KEY = "JSGridItem", JSGRID_EDIT_ROW_DATA_KEY = "JSGridEditRow", SORT_ORDER_ASC = "asc", SORT_ORDER_DESC = "desc", FIRST_PAGE_PLACEHOLDER = "{first}", PAGES_PLACEHOLDER = "{pages}", PREV_PAGE_PLACEHOLDER = "{prev}", NEXT_PAGE_PLACEHOLDER = "{next}", LAST_PAGE_PLACEHOLDER = "{last}", PAGE_INDEX_PLACEHOLDER = "{pageIndex}", PAGE_COUNT_PLACEHOLDER = "{pageCount}", ITEM_COUNT_PLACEHOLDER = "{itemCount}", EMPTY_HREF = "javascript:void(0);"; var getOrApply = function(value, context) { if($.isFunction(value)) { return value.apply(context, $.makeArray(arguments).slice(2)); } return value; }; var normalizePromise = function(promise) { var d = $.Deferred(); if(promise && promise.then) { promise.then(function() { d.resolve.apply(d, arguments); }, function() { d.reject.apply(d, arguments); }); } else { d.resolve(promise); } return d.promise(); }; var defaultController = { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }; function Grid(element, config) { var $element = $(element); $element.data(JSGRID_DATA_KEY, this); this._container = $element; this.data = []; this.fields = []; this._editingRow = null; this._sortField = null; this._sortOrder = SORT_ORDER_ASC; this._firstDisplayingPage = 1; this._init(config); this.render(); } Grid.prototype = { width: "auto", height: "auto", updateOnResize: true, rowClass: $.noop, rowRenderer: null, rowClick: function(args) { if(this.editing) { this.editItem($(args.event.target).closest("tr")); } }, rowDoubleClick: $.noop, noDataContent: "Not found", noDataRowClass: "jsgrid-nodata-row", heading: true, headerRowRenderer: null, headerRowClass: "jsgrid-header-row", headerCellClass: "jsgrid-header-cell", filtering: false, filterRowRenderer: null, filterRowClass: "jsgrid-filter-row", inserting: false, insertRowLocation: "bottom", insertRowRenderer: null, insertRowClass: "jsgrid-insert-row", editing: false, editRowRenderer: null, editRowClass: "jsgrid-edit-row", confirmDeleting: true, deleteConfirm: "Are you sure?", selecting: true, selectedRowClass: "jsgrid-selected-row", oddRowClass: "jsgrid-row", evenRowClass: "jsgrid-alt-row", cellClass: "jsgrid-cell", sorting: false, sortableClass: "jsgrid-header-sortable", sortAscClass: "jsgrid-header-sort jsgrid-header-sort-asc", sortDescClass: "jsgrid-header-sort jsgrid-header-sort-desc", paging: false, pagerContainer: null, pageIndex: 1, pageSize: 20, pageButtonCount: 15, pagerFormat: "Pages: {first} {prev} {pages} {next} {last} &nbsp;&nbsp; {pageIndex} of {pageCount}", pagePrevText: "Prev", pageNextText: "Next", pageFirstText: "First", pageLastText: "Last", pageNavigatorNextText: "...", pageNavigatorPrevText: "...", pagerContainerClass: "jsgrid-pager-container", pagerClass: "jsgrid-pager", pagerNavButtonClass: "jsgrid-pager-nav-button", pagerNavButtonInactiveClass: "jsgrid-pager-nav-inactive-button", pageClass: "jsgrid-pager-page", currentPageClass: "jsgrid-pager-current-page", customLoading: false, pageLoading: false, autoload: false, controller: defaultController, loadIndication: true, loadIndicationDelay: 500, loadMessage: "Please, wait...", loadShading: true, invalidMessage: "Invalid data entered!", invalidNotify: function(args) { var messages = $.map(args.errors, function(error) { return error.message || null; }); window.alert([this.invalidMessage].concat(messages).join("\n")); }, onInit: $.noop, onRefreshing: $.noop, onRefreshed: $.noop, onPageChanged: $.noop, onItemDeleting: $.noop, onItemDeleted: $.noop, onItemInserting: $.noop, onItemInserted: $.noop, onItemEditing: $.noop, onItemEditCancelling: $.noop, onItemUpdating: $.noop, onItemUpdated: $.noop, onItemInvalid: $.noop, onDataLoading: $.noop, onDataLoaded: $.noop, onDataExporting: $.noop, onOptionChanging: $.noop, onOptionChanged: $.noop, onError: $.noop, invalidClass: "jsgrid-invalid", containerClass: "jsgrid", tableClass: "jsgrid-table", gridHeaderClass: "jsgrid-grid-header", gridBodyClass: "jsgrid-grid-body", _init: function(config) { $.extend(this, config); this._initLoadStrategy(); this._initController(); this._initFields(); this._attachWindowLoadResize(); this._attachWindowResizeCallback(); this._callEventHandler(this.onInit) }, loadStrategy: function() { return this.pageLoading ? new jsGrid.loadStrategies.PageLoadingStrategy(this) : new jsGrid.loadStrategies.DirectLoadingStrategy(this); }, _initLoadStrategy: function() { this._loadStrategy = getOrApply(this.loadStrategy, this); }, _initController: function() { this._controller = $.extend({}, defaultController, getOrApply(this.controller, this)); }, renderTemplate: function(source, context, config) { var args = []; for(var key in config) { args.push(config[key]); } args.unshift(source, context); source = getOrApply.apply(null, args); return (source === undefined || source === null) ? "" : source; }, loadIndicator: function(config) { return new jsGrid.LoadIndicator(config); }, validation: function(config) { return jsGrid.Validation && new jsGrid.Validation(config); }, _initFields: function() { var self = this; self.fields = $.map(self.fields, function(field) { if($.isPlainObject(field)) { var fieldConstructor = (field.type && jsGrid.fields[field.type]) || jsGrid.Field; field = new fieldConstructor(field); } field._grid = self; return field; }); }, _attachWindowLoadResize: function() { $(window).on("load", $.proxy(this._refreshSize, this)); }, _attachWindowResizeCallback: function() { if(this.updateOnResize) { $(window).on("resize", $.proxy(this._refreshSize, this)); } }, _detachWindowResizeCallback: function() { $(window).off("resize", this._refreshSize); }, option: function(key, value) { var optionChangingEventArgs, optionChangedEventArgs; if(arguments.length === 1) return this[key]; optionChangingEventArgs = { option: key, oldValue: this[key], newValue: value }; this._callEventHandler(this.onOptionChanging, optionChangingEventArgs); this._handleOptionChange(optionChangingEventArgs.option, optionChangingEventArgs.newValue); optionChangedEventArgs = { option: optionChangingEventArgs.option, value: optionChangingEventArgs.newValue }; this._callEventHandler(this.onOptionChanged, optionChangedEventArgs); }, fieldOption: function(field, key, value) { field = this._normalizeField(field); if(arguments.length === 2) return field[key]; field[key] = value; this._renderGrid(); }, _handleOptionChange: function(name, value) { this[name] = value; switch(name) { case "width": case "height": this._refreshSize(); break; case "rowClass": case "rowRenderer": case "rowClick": case "rowDoubleClick": case "noDataRowClass": case "noDataContent": case "selecting": case "selectedRowClass": case "oddRowClass": case "evenRowClass": this._refreshContent(); break; case "pageButtonCount": case "pagerFormat": case "pagePrevText": case "pageNextText": case "pageFirstText": case "pageLastText": case "pageNavigatorNextText": case "pageNavigatorPrevText": case "pagerClass": case "pagerNavButtonClass": case "pageClass": case "currentPageClass": case "pagerRenderer": this._refreshPager(); break; case "fields": this._initFields(); this.render(); break; case "data": case "editing": case "heading": case "filtering": case "inserting": case "paging": this.refresh(); break; case "loadStrategy": case "pageLoading": this._initLoadStrategy(); this.search(); break; case "pageIndex": this.openPage(value); break; case "pageSize": this.refresh(); this.search(); break; case "editRowRenderer": case "editRowClass": this.cancelEdit(); break; case "updateOnResize": this._detachWindowResizeCallback(); this._attachWindowResizeCallback(); break; case "invalidNotify": case "invalidMessage": break; default: this.render(); break; } }, destroy: function() { this._detachWindowResizeCallback(); this._clear(); this._container.removeData(JSGRID_DATA_KEY); }, render: function() { this._renderGrid(); return this.autoload ? this.loadData() : $.Deferred().resolve().promise(); }, _renderGrid: function() { this._clear(); this._container.addClass(this.containerClass) .css("position", "relative") .append(this._createHeader()) .append(this._createBody()); this._pagerContainer = this._createPagerContainer(); this._loadIndicator = this._createLoadIndicator(); this._validation = this._createValidation(); this.refresh(); }, _createLoadIndicator: function() { return getOrApply(this.loadIndicator, this, { message: this.loadMessage, shading: this.loadShading, container: this._container }); }, _createValidation: function() { return getOrApply(this.validation, this); }, _clear: function() { this.cancelEdit(); clearTimeout(this._loadingTimer); this._pagerContainer && this._pagerContainer.empty(); this._container.empty() .css({ position: "", width: "", height: "" }); }, _createHeader: function() { var $headerRow = this._headerRow = this._createHeaderRow(), $filterRow = this._filterRow = this._createFilterRow(), $insertRow = this._insertRow = this._createInsertRow(); var $headerGrid = this._headerGrid = $("<table>").addClass(this.tableClass) .append($headerRow) .append($filterRow) .append($insertRow); var $header = this._header = $("<div>").addClass(this.gridHeaderClass) .addClass(this._scrollBarWidth() ? "jsgrid-header-scrollbar" : "") .append($headerGrid); return $header; }, _createBody: function() { var $content = this._content = $("<tbody>"); var $bodyGrid = this._bodyGrid = $("<table>").addClass(this.tableClass) .append($content); var $body = this._body = $("<div>").addClass(this.gridBodyClass) .append($bodyGrid) .on("scroll", $.proxy(function(e) { this._header.scrollLeft(e.target.scrollLeft); }, this)); return $body; }, _createPagerContainer: function() { var pagerContainer = this.pagerContainer || $("<div>").appendTo(this._container); return $(pagerContainer).addClass(this.pagerContainerClass); }, _eachField: function(callBack) { var self = this; $.each(this.fields, function(index, field) { if(field.visible) { callBack.call(self, field, index); } }); }, _createHeaderRow: function() { if($.isFunction(this.headerRowRenderer)) return $(this.renderTemplate(this.headerRowRenderer, this)); var $result = $("<tr>").addClass(this.headerRowClass); this._eachField(function(field, index) { var $th = this._prepareCell("<th>", field, "headercss", this.headerCellClass) .append(this.renderTemplate(field.headerTemplate, field)) .appendTo($result); if(this.sorting && field.sorting) { $th.addClass(this.sortableClass) .on("click", $.proxy(function() { this.sort(index); }, this)); } }); return $result; }, _prepareCell: function(cell, field, cssprop, cellClass) { return $(cell).css("width", field.width) .addClass(cellClass || this.cellClass) .addClass((cssprop && field[cssprop]) || field.css) .addClass(field.align ? ("jsgrid-align-" + field.align) : ""); }, _createFilterRow: function() { if($.isFunction(this.filterRowRenderer)) return $(this.renderTemplate(this.filterRowRenderer, this)); var $result = $("<tr>").addClass(this.filterRowClass); this._eachField(function(field) { this._prepareCell("<td>", field, "filtercss") .append(this.renderTemplate(field.filterTemplate, field)) .appendTo($result); }); return $result; }, _createInsertRow: function() { if($.isFunction(this.insertRowRenderer)) return $(this.renderTemplate(this.insertRowRenderer, this)); var $result = $("<tr>").addClass(this.insertRowClass); this._eachField(function(field) { this._prepareCell("<td>", field, "insertcss") .append(this.renderTemplate(field.insertTemplate, field)) .appendTo($result); }); return $result; }, _callEventHandler: function(handler, eventParams) { handler.call(this, $.extend(eventParams, { grid: this })); return eventParams; }, reset: function() { this._resetSorting(); this._resetPager(); return this._loadStrategy.reset(); }, _resetPager: function() { this._firstDisplayingPage = 1; this._setPage(1); }, _resetSorting: function() { this._sortField = null; this._sortOrder = SORT_ORDER_ASC; this._clearSortingCss(); }, refresh: function() { this._callEventHandler(this.onRefreshing); this.cancelEdit(); this._refreshHeading(); this._refreshFiltering(); this._refreshInserting(); this._refreshContent(); this._refreshPager(); this._refreshSize(); this._callEventHandler(this.onRefreshed); }, _refreshHeading: function() { this._headerRow.toggle(this.heading); }, _refreshFiltering: function() { this._filterRow.toggle(this.filtering); }, _refreshInserting: function() { this._insertRow.toggle(this.inserting); }, _refreshContent: function() { var $content = this._content; $content.empty(); if(!this.data.length) { $content.append(this._createNoDataRow()); return this; } var indexFrom = this._loadStrategy.firstDisplayIndex(); var indexTo = this._loadStrategy.lastDisplayIndex(); for(var itemIndex = indexFrom; itemIndex < indexTo; itemIndex++) { var item = this.data[itemIndex]; $content.append(this._createRow(item, itemIndex)); } }, _createNoDataRow: function() { var amountOfFields = 0; this._eachField(function() { amountOfFields++; }); return $("<tr>").addClass(this.noDataRowClass) .append($("<td>").addClass(this.cellClass).attr("colspan", amountOfFields) .append(this.renderTemplate(this.noDataContent, this))); }, _createRow: function(item, itemIndex) { var $result; if($.isFunction(this.rowRenderer)) { $result = this.renderTemplate(this.rowRenderer, this, { item: item, itemIndex: itemIndex }); } else { $result = $("<tr>"); this._renderCells($result, item); } $result.addClass(this._getRowClasses(item, itemIndex)) .data(JSGRID_ROW_DATA_KEY, item) .on("click", $.proxy(function(e) { $result = $("<td>").append(field.itemTemplate ? field.itemTemplate(fieldValue, item) : fieldValue); } $result.addClass(field.css) .width(field.width); field.align && $result.addClass("jsgrid-align-" + field.align); itemIndex: itemIndex, event: e }); }, this)); if(this.selecting) { this._attachRowHover($result); } return $result; }, _getRowClasses: function(item, itemIndex) { var classes = []; classes.push(((itemIndex + 1) % 2) ? this.oddRowClass : this.evenRowClass); classes.push(getOrApply(this.rowClass, this, item, itemIndex)); return classes.join(" "); }, _attachRowHover: function($row) { var selectedRowClass = this.selectedRowClass; $row.hover(function() { $(this).addClass(selectedRowClass); }, function() { $(this).removeClass(selectedRowClass); } ); }, _renderCells: function($row, item) { this._eachField(function(field) { $row.append(this._createCell(item, field)); }); return this; }, _createCell: function(item, field) { var $result; var fieldValue = this._getItemFieldValue(item, field); var args = { value: fieldValue, item : item }; if($.isFunction(field.cellRenderer)) { $result = this.renderTemplate(field.cellRenderer, field, args); } else { $result = $("<td>").append(this.renderTemplate(field.itemTemplate || fieldValue, field, args)); } return this._prepareCell($result, field); }, _getItemFieldValue: function(item, field) { var props = field.name.split('.'); var result = item[props.shift()]; while(result && props.length) { result = result[props.shift()]; } return result; }, _setItemFieldValue: function(item, field, value) { var props = field.name.split('.'); var current = item; var prop = props[0]; while(current && props.length) { item = current; prop = props.shift(); current = item[prop]; } if(!current) { while(props.length) { item = item[prop] = {}; prop = props.shift(); } } item[prop] = value; }, sort: function(field, order) { if($.isPlainObject(field)) { order = field.order; field = field.field; } this._clearSortingCss(); this._setSortingParams(field, order); this._setSortingCss(); return this._loadStrategy.sort(); }, _clearSortingCss: function() { this._headerRow.find("th") .removeClass(this.sortAscClass) .removeClass(this.sortDescClass); }, _setSortingParams: function(field, order) { field = this._normalizeField(field); order = order || ((this._sortField === field) ? this._reversedSortOrder(this._sortOrder) : SORT_ORDER_ASC); this._sortField = field; this._sortOrder = order; }, _normalizeField: function(field) { if($.isNumeric(field)) { return this.fields[field]; } if(typeof field === "string") { return $.grep(this.fields, function(f) { return f.name === field; })[0]; } return field; }, _reversedSortOrder: function(order) { return (order === SORT_ORDER_ASC ? SORT_ORDER_DESC : SORT_ORDER_ASC); }, _setSortingCss: function() { var fieldIndex = this._visibleFieldIndex(this._sortField); this._headerRow.find("th").eq(fieldIndex) .addClass(this._sortOrder === SORT_ORDER_ASC ? this.sortAscClass : this.sortDescClass); }, _visibleFieldIndex: function(field) { return $.inArray(field, $.grep(this.fields, function(f) { return f.visible; })); }, _sortData: function() { var sortFactor = this._sortFactor(), sortField = this._sortField; if(sortField) { var self = this; self.data.sort(function(item1, item2) { var value1 = self._getItemFieldValue(item1, sortField); var value2 = self._getItemFieldValue(item2, sortField); return sortFactor * sortField.sortingFunc(value1, value2); }); } }, _sortFactor: function() { return this._sortOrder === SORT_ORDER_ASC ? 1 : -1; }, _itemsCount: function() { return this._loadStrategy.itemsCount(); }, _pagesCount: function() { var itemsCount = this._itemsCount(), pageSize = this.pageSize; return Math.floor(itemsCount / pageSize) + (itemsCount % pageSize ? 1 : 0); }, _refreshPager: function() { var $pagerContainer = this._pagerContainer; $pagerContainer.empty(); if(this.paging) { $pagerContainer.append(this._createPager()); } var showPager = this.paging && this._pagesCount() > 1; $pagerContainer.toggle(showPager); }, _createPager: function() { var $result; if($.isFunction(this.pagerRenderer)) { $result = $(this.pagerRenderer({ pageIndex: this.pageIndex, pageCount: this._pagesCount() })); } else { $result = $("<div>").append(this._createPagerByFormat()); } $result.addClass(this.pagerClass); return $result; }, _createPagerByFormat: function() { var pageIndex = this.pageIndex, pageCount = this._pagesCount(), itemCount = this._itemsCount(), pagerParts = this.pagerFormat.split(" "); return $.map(pagerParts, $.proxy(function(pagerPart) { var result = pagerPart; if(pagerPart === PAGES_PLACEHOLDER) { result = this._createPages(); } else if(pagerPart === FIRST_PAGE_PLACEHOLDER) { result = this._createPagerNavButton(this.pageFirstText, 1, pageIndex > 1); } else if(pagerPart === PREV_PAGE_PLACEHOLDER) { result = this._createPagerNavButton(this.pagePrevText, pageIndex - 1, pageIndex > 1); } else if(pagerPart === NEXT_PAGE_PLACEHOLDER) { result = this._createPagerNavButton(this.pageNextText, pageIndex + 1, pageIndex < pageCount); } else if(pagerPart === LAST_PAGE_PLACEHOLDER) { result = this._createPagerNavButton(this.pageLastText, pageCount, pageIndex < pageCount); } else if(pagerPart === PAGE_INDEX_PLACEHOLDER) { result = pageIndex; } else if(pagerPart === PAGE_COUNT_PLACEHOLDER) { result = pageCount; } else if(pagerPart === ITEM_COUNT_PLACEHOLDER) { result = itemCount; } return $.isArray(result) ? result.concat([" "]) : [result, " "]; }, this)); }, _createPages: function() { var pageCount = this._pagesCount(), pageButtonCount = this.pageButtonCount, firstDisplayingPage = this._firstDisplayingPage, pages = []; if(firstDisplayingPage > 1) { pages.push(this._createPagerPageNavButton(this.pageNavigatorPrevText, this.showPrevPages)); } for(var i = 0, pageNumber = firstDisplayingPage; i < pageButtonCount && pageNumber <= pageCount; i++, pageNumber++) { pages.push(pageNumber === this.pageIndex ? this._createPagerCurrentPage() : this._createPagerPage(pageNumber)); } if((firstDisplayingPage + pageButtonCount - 1) < pageCount) { pages.push(this._createPagerPageNavButton(this.pageNavigatorNextText, this.showNextPages)); } return pages; }, _createPagerNavButton: function(text, pageIndex, isActive) { return this._createPagerButton(text, this.pagerNavButtonClass + (isActive ? "" : " " + this.pagerNavButtonInactiveClass), isActive ? function() { this.openPage(pageIndex); } : $.noop); }, _createPagerPageNavButton: function(text, handler) { return this._createPagerButton(text, this.pagerNavButtonClass, handler); }, _createPagerPage: function(pageIndex) { return this._createPagerButton(pageIndex, this.pageClass, function() { this.openPage(pageIndex); }); }, _createPagerButton: function(text, css, handler) { var $link = $("<a>").attr("href", EMPTY_HREF) .html(text) .on("click", $.proxy(handler, this)); return $("<span>").addClass(css).append($link); }, _createPagerCurrentPage: function() { return $("<span>") .addClass(this.pageClass) .addClass(this.currentPageClass) .text(this.pageIndex); }, _refreshSize: function() { this._refreshHeight(); this._refreshWidth(); }, _refreshWidth: function() { var width = (this.width === "auto") ? this._getAutoWidth() : this.width; this._container.width(width); }, _getAutoWidth: function() { var $headerGrid = this._headerGrid, $header = this._header; $headerGrid.width("auto"); var contentWidth = $headerGrid.outerWidth(); var borderWidth = $header.outerWidth() - $header.innerWidth(); $headerGrid.width(""); return contentWidth + borderWidth; }, _scrollBarWidth: (function() { var result; return function() { if(result === undefined) { var $ghostContainer = $("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>"); var $ghostContent = $("<div style='height:100px;'></div>"); $ghostContainer.append($ghostContent).appendTo("body"); var width = $ghostContent.innerWidth(); $ghostContainer.css("overflow-y", "auto"); var widthExcludingScrollBar = $ghostContent.innerWidth(); $ghostContainer.remove(); result = width - widthExcludingScrollBar; } return result; }; })(), _refreshHeight: function() { var container = this._container, pagerContainer = this._pagerContainer, height = this.height, nonBodyHeight; container.height(height); if(height !== "auto") { height = container.height(); nonBodyHeight = this._header.outerHeight(true); if(pagerContainer.parents(container).length) { nonBodyHeight += pagerContainer.outerHeight(true); } this._body.outerHeight(height - nonBodyHeight); } }, showPrevPages: function() { var firstDisplayingPage = this._firstDisplayingPage, pageButtonCount = this.pageButtonCount; this._firstDisplayingPage = (firstDisplayingPage > pageButtonCount) ? firstDisplayingPage - pageButtonCount : 1; this._refreshPager(); }, showNextPages: function() { var firstDisplayingPage = this._firstDisplayingPage, pageButtonCount = this.pageButtonCount, pageCount = this._pagesCount(); this._firstDisplayingPage = (firstDisplayingPage + 2 * pageButtonCount > pageCount) ? pageCount - pageButtonCount + 1 : firstDisplayingPage + pageButtonCount; this._refreshPager(); }, openPage: function(pageIndex) { if(pageIndex < 1 || pageIndex > this._pagesCount()) return; this._setPage(pageIndex); this._loadStrategy.openPage(pageIndex); }, _setPage: function(pageIndex) { var firstDisplayingPage = this._firstDisplayingPage, pageButtonCount = this.pageButtonCount; this.pageIndex = pageIndex; if(pageIndex < firstDisplayingPage) { this._firstDisplayingPage = pageIndex; } if(pageIndex > firstDisplayingPage + pageButtonCount - 1) { this._firstDisplayingPage = pageIndex - pageButtonCount + 1; } this._callEventHandler(this.onPageChanged, { pageIndex: pageIndex }); }, _controllerCall: function(method, param, isCanceled, doneCallback) { if(isCanceled) return $.Deferred().reject().promise(); this._showLoading(); var controller = this._controller; if(!controller || !controller[method]) { throw Error("controller has no method '" + method + "'"); } return normalizePromise(controller[method](param)) .done($.proxy(doneCallback, this)) .fail($.proxy(this._errorHandler, this)) .always($.proxy(this._hideLoading, this)); }, _errorHandler: function() { this._callEventHandler(this.onError, { args: $.makeArray(arguments) }); }, _showLoading: function() { if(!this.loadIndication) return; clearTimeout(this._loadingTimer); this._loadingTimer = setTimeout($.proxy(function() { this._loadIndicator.show(); }, this), this.loadIndicationDelay); }, _hideLoading: function() { if(!this.loadIndication) return; clearTimeout(this._loadingTimer); this._loadIndicator.hide(); }, search: function(filter) { this._resetSorting(); this._resetPager(); return this.loadData(filter); }, loadData: function(filter) { filter = filter || (this.filtering ? this.getFilter() : {}); $.extend(filter, this._loadStrategy.loadParams(), this._sortingParams()); var args = this._callEventHandler(this.onDataLoading, { filter: filter }); return this._controllerCall("loadData", filter, args.cancel, function(loadedData) { if(!loadedData) return; this._loadStrategy.finishLoad(loadedData); this._callEventHandler(this.onDataLoaded, { data: loadedData }); }); }, exportData: function(exportOptions){ var options = exportOptions || {}; var type = options.type || "csv"; var result = ""; this._callEventHandler(this.onDataExporting); switch(type){ case "csv": result = this._dataToCsv(options); break; } return result; }, _dataToCsv: function(options){ var options = options || {}; var includeHeaders = options.hasOwnProperty("includeHeaders") ? options.includeHeaders : true; var subset = options.subset || "all"; var filter = options.filter || undefined; var result = []; if (includeHeaders){ var fieldsLength = this.fields.length; var fieldNames = {}; for(var i=0;i<fieldsLength;i++){ var field = this.fields[i]; if ("includeInDataExport" in field){ if (field.includeInDataExport === true) fieldNames[i] = field.title || field.name; } } var headerLine = this._itemToCsv(fieldNames,{},options); result.push(headerLine); } var exportStartIndex = 0; var exportEndIndex = this.data.length; switch(subset){ case "visible": exportEndIndex = this._firstDisplayingPage * this.pageSize; exportStartIndex = exportEndIndex - this.pageSize; case "all": default: break; } for (var i = exportStartIndex; i < exportEndIndex; i++){ var item = this.data[i]; var itemLine = ""; var includeItem = true; if (filter) if (!filter(item)) includeItem = false; if (includeItem){ itemLine = this._itemToCsv(item, this.fields, options); result.push(itemLine); } } return result.join(""); }, _itemToCsv: function(item, fields, options){ var options = options || {}; var delimiter = options.delimiter || "|"; var encapsulate = options.hasOwnProperty("encapsulate") ? options.encapsulate : true; var newline = options.newline || "\r\n"; var transforms = options.transforms || {}; var fields = fields || {}; var getItem = this._getItemFieldValue; var result = []; Object.keys(item).forEach(function(key,index) { var entry = ""; //Fields.length is greater than 0 when we are matching agaisnt fields //Field.length will be 0 when exporting header rows if (fields.length > 0){ var field = fields[index]; //Field may be excluded from data export if ("includeInDataExport" in field){ if (field.includeInDataExport){ //Field may be a select, which requires additional logic if (field.type === "select"){ var selectedItem = getItem(item, field); var resultItem = $.grep(field.items, function(item, index) { return item[field.valueField] === selectedItem; })[0] || ""; entry = resultItem[field.textField]; } else{ entry = getItem(item, field); } } else{ return; } } else{ entry = getItem(item, field); } if (transforms.hasOwnProperty(field.name)){ entry = transforms[field.name](entry); } } else{ entry = item[key]; } if (encapsulate){ entry = '"'+entry+'"'; } result.push(entry); }); return result.join(delimiter) + newline; }, getFilter: function() { var result = {}; this._eachField(function(field) { if(field.filtering) { this._setItemFieldValue(result, field, field.filterValue()); } }); return result; }, _sortingParams: function() { if(this.sorting && this._sortField) { return { sortField: this._sortField.name, sortOrder: this._sortOrder }; } return {}; }, getSorting: function() { var sortingParams = this._sortingParams(); return { field: sortingParams.sortField, order: sortingParams.sortOrder }; }, clearFilter: function() { var $filterRow = this._createFilterRow(); this._filterRow.replaceWith($filterRow); this._filterRow = $filterRow; return this.search(); }, insertItem: function(item) { var insertingItem = item || this._getValidatedInsertItem(); if(!insertingItem) return $.Deferred().reject().promise(); var args = this._callEventHandler(this.onItemInserting, { item: insertingItem }); return this._controllerCall("insertItem", insertingItem, args.cancel, function(insertedItem) { insertedItem = insertedItem || insertingItem; this._loadStrategy.finishInsert(insertedItem, this.insertRowLocation); this._callEventHandler(this.onItemInserted, { item: insertedItem }); }); }, _getValidatedInsertItem: function() { var item = this._getInsertItem(); return this._validateItem(item, this._insertRow) ? item : null; }, _getInsertItem: function() { var result = {}; this._eachField(function(field) { if(field.inserting) { this._setItemFieldValue(result, field, field.insertValue()); } }); return result; }, _validateItem: function(item, $row) { var validationErrors = []; var args = { item: item, itemIndex: this._rowIndex($row), row: $row }; this._eachField(function(field) { if(!field.validate || ($row === this._insertRow && !field.inserting) || ($row === this._getEditRow() && !field.editing)) return; var fieldValue = this._getItemFieldValue(item, field); var errors = this._validation.validate($.extend({ value: fieldValue, rules: field.validate }, args)); this._setCellValidity($row.children().eq(this._visibleFieldIndex(field)), errors); if(!errors.length) return; validationErrors.push.apply(validationErrors, $.map(errors, function(message) { return { field: field, message: message }; })); }); if(!validationErrors.length) return true; var invalidArgs = $.extend({ errors: validationErrors }, args); this._callEventHandler(this.onItemInvalid, invalidArgs); this.invalidNotify(invalidArgs); return false; }, _setCellValidity: function($cell, errors) { $cell .toggleClass(this.invalidClass, !!errors.length) .attr("title", errors.join("\n")); }, clearInsert: function() { var insertRow = this._createInsertRow(); this._insertRow.replaceWith(insertRow); this._insertRow = insertRow; this.refresh(); }, editItem: function(item) { var $row = this.rowByItem(item); if($row.length) { this._editRow($row); } }, rowByItem: function(item) { if(item.jquery || item.nodeType) return $(item); return this._content.find("tr").filter(function() { return $.data(this, JSGRID_ROW_DATA_KEY) === item; }); }, _editRow: function($row) { if(!this.editing) return; var item = $row.data(JSGRID_ROW_DATA_KEY); var args = this._callEventHandler(this.onItemEditing, { row: $row, item: item, itemIndex: this._itemIndex(item) }); if(args.cancel) return; if(this._editingRow) { this.cancelEdit(); } var $editRow = this._createEditRow(item); this._editingRow = $row; $row.hide(); $editRow.insertBefore($row); $row.data(JSGRID_EDIT_ROW_DATA_KEY, $editRow); }, _createEditRow: function(item) { if($.isFunction(this.editRowRenderer)) { return $(this.renderTemplate(this.editRowRenderer, this, { item: item, itemIndex: this._itemIndex(item) })); } var $result = $("<tr>").addClass(this.editRowClass); this._eachField(function(field) { var fieldValue = this._getItemFieldValue(item, field); this._prepareCell("<td>", field, "editcss") .append(this.renderTemplate(field.editTemplate || "", field, { value: fieldValue, item: item })) .appendTo($result); }); return $result; }, updateItem: function(item, editedItem) { if(arguments.length === 1) { editedItem = item; } var $row = item ? this.rowByItem(item) : this._editingRow; editedItem = editedItem || this._getValidatedEditedItem(); if(!editedItem) return; return this._updateRow($row, editedItem); }, _getValidatedEditedItem: function() { var item = this._getEditedItem(); return this._validateItem(item, this._getEditRow()) ? item : null; }, _updateRow: function($updatingRow, editedItem) { var updatingItem = $updatingRow.data(JSGRID_ROW_DATA_KEY), updatingItemIndex = this._itemIndex(updatingItem), updatedItem = $.extend(true, {}, updatingItem, editedItem); var args = this._callEventHandler(this.onItemUpdating, { row: $updatingRow, item: updatedItem, itemIndex: updatingItemIndex, previousItem: updatingItem }); return this._controllerCall("updateItem", updatedItem, args.cancel, function(loadedUpdatedItem) { var previousItem = $.extend(true, {}, updatingItem); updatedItem = loadedUpdatedItem || $.extend(true, updatingItem, editedItem); var $updatedRow = this._finishUpdate($updatingRow, updatedItem, updatingItemIndex); this._callEventHandler(this.onItemUpdated, { row: $updatedRow, item: updatedItem, itemIndex: updatingItemIndex, previousItem: previousItem }); }); }, _rowIndex: function(row) { return this._content.children().index($(row)); }, _itemIndex: function(item) { return $.inArray(item, this.data); }, _finishUpdate: function($updatingRow, updatedItem, updatedItemIndex) { this.cancelEdit(); this.data[updatedItemIndex] = updatedItem; var $updatedRow = this._createRow(updatedItem, updatedItemIndex); $updatingRow.replaceWith($updatedRow); return $updatedRow; }, _getEditedItem: function() { var result = {}; this._eachField(function(field) { if(field.editing) { this._setItemFieldValue(result, field, field.editValue()); } }); return result; }, cancelEdit: function() { if(!this._editingRow) return; var $row = this._editingRow, editingItem = $row.data(JSGRID_ROW_DATA_KEY), editingItemIndex = this._itemIndex(editingItem); this._callEventHandler(this.onItemEditCancelling, { row: $row, item: editingItem, itemIndex: editingItemIndex }); this._getEditRow().remove(); this._editingRow.show(); this._editingRow = null; }, _getEditRow: function() { return this._editingRow && this._editingRow.data(JSGRID_EDIT_ROW_DATA_KEY); }, deleteItem: function(item) { var $row = this.rowByItem(item); if(!$row.length) return; if(this.confirmDeleting && !window.confirm(getOrApply(this.deleteConfirm, this, $row.data(JSGRID_ROW_DATA_KEY)))) return; return this._deleteRow($row); }, _deleteRow: function($row) { var deletingItem = $row.data(JSGRID_ROW_DATA_KEY), deletingItemIndex = this._itemIndex(deletingItem); var args = this._callEventHandler(this.onItemDeleting, { row: $row, item: deletingItem, itemIndex: deletingItemIndex }); return this._controllerCall("deleteItem", deletingItem, args.cancel, function() { this._loadStrategy.finishDelete(deletingItem, deletingItemIndex); this._callEventHandler(this.onItemDeleted, { row: $row, item: deletingItem, itemIndex: deletingItemIndex }); }); } }; $.fn.jsGrid = function(config) { var args = $.makeArray(arguments), methodArgs = args.slice(1), result = this; this.each(function() { var $element = $(this), instance = $element.data(JSGRID_DATA_KEY), methodResult; if(instance) { if(typeof config === "string") { methodResult = instance[config].apply(instance, methodArgs); if(methodResult !== undefined && methodResult !== instance) { result = methodResult; return false; } } else { instance._detachWindowResizeCallback(); instance._init(config); instance.render(); } } else { new Grid($element, config); } }); return result; }; var fields = {}; var setDefaults = function(config) { var componentPrototype; if($.isPlainObject(config)) { componentPrototype = Grid.prototype; } else { componentPrototype = fields[config].prototype; config = arguments[1] || {}; } $.extend(componentPrototype, config); }; var locales = {}; var locale = function(lang) { var localeConfig = $.isPlainObject(lang) ? lang : locales[lang]; if(!localeConfig) throw Error("unknown locale " + lang); setLocale(jsGrid, localeConfig); }; var setLocale = function(obj, localeConfig) { $.each(localeConfig, function(field, value) { if($.isPlainObject(value)) { setLocale(obj[field] || obj[field[0].toUpperCase() + field.slice(1)], value); return; } if(obj.hasOwnProperty(field)) { obj[field] = value; } else { obj.prototype[field] = value; } }); }; window.jsGrid = { Grid: Grid, fields: fields, setDefaults: setDefaults, locales: locales, locale: locale, version: "@VERSION" }; }(window, jQuery)); <MSG> Merge pull request #140 from sockhead/master Fix: Firefox td width issue <DFF> @@ -616,8 +616,9 @@ $result = $("<td>").append(field.itemTemplate ? field.itemTemplate(fieldValue, item) : fieldValue); } - $result.addClass(field.css) - .width(field.width); + $result.addClass(field.css); + $result.css({"width": field.width}); + field.align && $result.addClass("jsgrid-align-" + field.align);
3
Merge pull request #140 from sockhead/master
2
.js
core
mit
tabalinas/jsgrid
10068068
<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 * @return {String} * @api private */ proto._wrapHTML = function(html) { return '<' + this.tag + ' class="' + this._classes().join(' ') + '" id="' + this._fmid + '">' + html + '</' + this.tag + '>'; }; /** * Gets a space separated list * of all a view's classes * * @return {String} * @api private */ proto._classes = function() { return [this.module()].concat(this.classes); }; /** * Renders the view and replaces * the `view.el` with a freshly * rendered node. * * Fires a `render` event on the view. if (this.el && this.el.tagName === this.tag.toUpperCase()) { this.el.innerHTML = this._innerHTML(); this.el.className = this._classes(); } else { // Sets a new element as a view's // root element (purging descendent // element caches). this._setEl(util.toNode(this.toHTML())); } 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> Consistent comments <DFF> @@ -553,11 +553,11 @@ module.exports = function(fm) { if (this.el && this.el.tagName === this.tag.toUpperCase()) { this.el.innerHTML = this._innerHTML(); this.el.className = this._classes(); - } else { - // Sets a new element as a view's - // root element (purging descendent - // element caches). + // Sets a new element as a view's + // root element (purging descendent + // element caches). + } else { this._setEl(util.toNode(this.toHTML())); }
4
Consistent comments
4
.js
js
mit
ftlabs/fruitmachine
10068069
<NME> README.md <BEF> # AvaloniaEdit This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). * 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: - [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) - [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/) Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars. ```csharp //First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. var _textEditor = this.FindControl<TextEditor>("Editor"); //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> Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1 Update README <DFF> @@ -1,4 +1,18 @@ +[![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 is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). +This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) 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 + * Line numeration + * Scrolling below document + * Hyperlinks + + and many,many more! + +![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) +
15
Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10068070
<NME> README.md <BEF> # AvaloniaEdit This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). * 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: - [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) - [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/) Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars. ```csharp //First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. var _textEditor = this.FindControl<TextEditor>("Editor"); //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> Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1 Update README <DFF> @@ -1,4 +1,18 @@ +[![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 is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). +This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) 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 + * Line numeration + * Scrolling below document + * Hyperlinks + + and many,many more! + +![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) +
15
Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10068071
<NME> README.md <BEF> # AvaloniaEdit This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). * 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: - [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) - [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/) Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars. ```csharp //First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. var _textEditor = this.FindControl<TextEditor>("Editor"); //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> Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1 Update README <DFF> @@ -1,4 +1,18 @@ +[![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 is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). +This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) 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 + * Line numeration + * Scrolling below document + * Hyperlinks + + and many,many more! + +![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) +
15
Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10068072
<NME> README.md <BEF> # AvaloniaEdit This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). * 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: - [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) - [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/) Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars. ```csharp //First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. var _textEditor = this.FindControl<TextEditor>("Editor"); //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> Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1 Update README <DFF> @@ -1,4 +1,18 @@ +[![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 is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). +This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) 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 + * Line numeration + * Scrolling below document + * Hyperlinks + + and many,many more! + +![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) +
15
Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10068073
<NME> README.md <BEF> # AvaloniaEdit This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). * 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: - [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) - [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/) Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars. ```csharp //First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. var _textEditor = this.FindControl<TextEditor>("Editor"); //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> Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1 Update README <DFF> @@ -1,4 +1,18 @@ +[![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 is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). +This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) 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 + * Line numeration + * Scrolling below document + * Hyperlinks + + and many,many more! + +![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) +
15
Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10068074
<NME> README.md <BEF> # AvaloniaEdit This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). * 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: - [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) - [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/) Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars. ```csharp //First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. var _textEditor = this.FindControl<TextEditor>("Editor"); //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> Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1 Update README <DFF> @@ -1,4 +1,18 @@ +[![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 is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). +This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) 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 + * Line numeration + * Scrolling below document + * Hyperlinks + + and many,many more! + +![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) +
15
Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10068075
<NME> README.md <BEF> # AvaloniaEdit This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). * 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: - [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) - [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/) Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars. ```csharp //First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. var _textEditor = this.FindControl<TextEditor>("Editor"); //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> Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1 Update README <DFF> @@ -1,4 +1,18 @@ +[![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 is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). +This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) 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 + * Line numeration + * Scrolling below document + * Hyperlinks + + and many,many more! + +![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) +
15
Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10068076
<NME> README.md <BEF> # AvaloniaEdit This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). * 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: - [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) - [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/) Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars. ```csharp //First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. var _textEditor = this.FindControl<TextEditor>("Editor"); //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> Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1 Update README <DFF> @@ -1,4 +1,18 @@ +[![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 is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). +This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) 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 + * Line numeration + * Scrolling below document + * Hyperlinks + + and many,many more! + +![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) +
15
Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10068077
<NME> README.md <BEF> # AvaloniaEdit This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). * 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: - [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) - [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/) Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars. ```csharp //First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. var _textEditor = this.FindControl<TextEditor>("Editor"); //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> Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1 Update README <DFF> @@ -1,4 +1,18 @@ +[![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 is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). +This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) 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 + * Line numeration + * Scrolling below document + * Hyperlinks + + and many,many more! + +![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) +
15
Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10068078
<NME> README.md <BEF> # AvaloniaEdit This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). * 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: - [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) - [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/) Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars. ```csharp //First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. var _textEditor = this.FindControl<TextEditor>("Editor"); //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> Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1 Update README <DFF> @@ -1,4 +1,18 @@ +[![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 is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). +This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) 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 + * Line numeration + * Scrolling below document + * Hyperlinks + + and many,many more! + +![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) +
15
Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10068079
<NME> README.md <BEF> # AvaloniaEdit This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). * 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: - [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) - [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/) Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars. ```csharp //First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. var _textEditor = this.FindControl<TextEditor>("Editor"); //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> Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1 Update README <DFF> @@ -1,4 +1,18 @@ +[![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 is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). +This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) 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 + * Line numeration + * Scrolling below document + * Hyperlinks + + and many,many more! + +![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) +
15
Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10068080
<NME> README.md <BEF> # AvaloniaEdit This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). * 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: - [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) - [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/) Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars. ```csharp //First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. var _textEditor = this.FindControl<TextEditor>("Editor"); //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> Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1 Update README <DFF> @@ -1,4 +1,18 @@ +[![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 is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). +This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) 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 + * Line numeration + * Scrolling below document + * Hyperlinks + + and many,many more! + +![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) +
15
Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10068081
<NME> README.md <BEF> # AvaloniaEdit This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). * 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: - [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) - [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/) Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars. ```csharp //First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. var _textEditor = this.FindControl<TextEditor>("Editor"); //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> Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1 Update README <DFF> @@ -1,4 +1,18 @@ +[![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 is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). +This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) 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 + * Line numeration + * Scrolling below document + * Hyperlinks + + and many,many more! + +![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) +
15
Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10068082
<NME> README.md <BEF> # AvaloniaEdit This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). * 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: - [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) - [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/) Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars. ```csharp //First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. var _textEditor = this.FindControl<TextEditor>("Editor"); //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> Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1 Update README <DFF> @@ -1,4 +1,18 @@ +[![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 is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). +This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) 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 + * Line numeration + * Scrolling below document + * Hyperlinks + + and many,many more! + +![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) +
15
Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10068083
<NME> README.md <BEF> # AvaloniaEdit This is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). * 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: - [AvaloniaEdit.TextMate](https://www.nuget.org/packages/AvaloniaEdit.TextMate/) - [TextMateSharp.Grammars](https://www.nuget.org/packages/TextMateSharp.Grammars/) Alternatively, if you want to support your own grammars, you just need to install the AvaloniaEdit.TextMate package, and implement IRegistryOptions interface, that's currently the easiest way in case you want to use AvaloniaEdit with the set of grammars different from in-bundled TextMateSharp.Grammars. ```csharp //First of all you need to have a reference for your TextEditor for it to be used inside AvaloniaEdit.TextMate project. var _textEditor = this.FindControl<TextEditor>("Editor"); //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> Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1 Update README <DFF> @@ -1,4 +1,18 @@ +[![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 is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) for [Avalonia](https://github.com/AvaloniaUI/Avalonia). +This project is a port of [AvalonEdit](https://github.com/icsharpcode/AvalonEdit) 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 + * Line numeration + * Scrolling below document + * Hyperlinks + + and many,many more! + +![image](https://user-images.githubusercontent.com/53405089/147930720-b388df7e-9b83-4ade-9338-6d311b334814.png) +
15
Merge pull request #176 from AvaloniaUI/Takoooooo-patch-1
1
.md
md
mit
AvaloniaUI/AvaloniaEdit
10068084
<NME> ja.js <BEF> ADDFILE <MSG> Add japanese translation. <DFF> @@ -0,0 +1,46 @@ +(function(jsGrid) { + + jsGrid.locales.ja = { + grid: { + noDataContent: "データが見つかりません。", + deleteConfirm: "削除しますよろしですか。", + pagerFormat: "頁: {first} {prev} {pages} {next} {last} &nbsp;&nbsp; 【{pageIndex}/{pageCount}】", + pagePrevText: "前", + pageNextText: "次", + pageFirstText: "最初", + pageLastText: "最後", + loadMessage: "しばらくお待ちください…", + invalidMessage: "入力されたデータが不正です。" + }, + + loadIndicator: { + message: "処理中…" + }, + + fields: { + control: { + searchModeButtonTooltip: "検索モードへ", + insertModeButtonTooltip: "登録モードへ", + editButtonTooltip: "編集", + deleteButtonTooltip: "削除", + searchButtonTooltip: "フィルター", + clearFilterButtonTooltip: "クリア", + insertButtonTooltip: "登録", + updateButtonTooltip: "更新", + cancelEditButtonTooltip: "編集戻す" + } + }, + + validators: { + required: { message: "項目が必要です。" }, + rangeLength: { message: "項目の桁数が範囲外です。" }, + minLength: { message: "項目の桁数が超過しています。" }, + maxLength: { message: "項目の桁数が不足しています。" }, + pattern: { message: "項目の値がパターンに一致しません。" }, + range: { message: "項目の値が範囲外です。" }, + min: { message: "項目の値が超過しています。" }, + max: { message: "項目の値が不足しています。" } + } + }; + +}(jsGrid, jQuery)); \ No newline at end of file
46
Add japanese translation.
0
.js
js
mit
tabalinas/jsgrid
10068085
<NME> ja.js <BEF> ADDFILE <MSG> Add japanese translation. <DFF> @@ -0,0 +1,46 @@ +(function(jsGrid) { + + jsGrid.locales.ja = { + grid: { + noDataContent: "データが見つかりません。", + deleteConfirm: "削除しますよろしですか。", + pagerFormat: "頁: {first} {prev} {pages} {next} {last} &nbsp;&nbsp; 【{pageIndex}/{pageCount}】", + pagePrevText: "前", + pageNextText: "次", + pageFirstText: "最初", + pageLastText: "最後", + loadMessage: "しばらくお待ちください…", + invalidMessage: "入力されたデータが不正です。" + }, + + loadIndicator: { + message: "処理中…" + }, + + fields: { + control: { + searchModeButtonTooltip: "検索モードへ", + insertModeButtonTooltip: "登録モードへ", + editButtonTooltip: "編集", + deleteButtonTooltip: "削除", + searchButtonTooltip: "フィルター", + clearFilterButtonTooltip: "クリア", + insertButtonTooltip: "登録", + updateButtonTooltip: "更新", + cancelEditButtonTooltip: "編集戻す" + } + }, + + validators: { + required: { message: "項目が必要です。" }, + rangeLength: { message: "項目の桁数が範囲外です。" }, + minLength: { message: "項目の桁数が超過しています。" }, + maxLength: { message: "項目の桁数が不足しています。" }, + pattern: { message: "項目の値がパターンに一致しません。" }, + range: { message: "項目の値が範囲外です。" }, + min: { message: "項目の値が超過しています。" }, + max: { message: "項目の値が不足しています。" } + } + }; + +}(jsGrid, jQuery)); \ No newline at end of file
46
Add japanese translation.
0
.js
js
mit
tabalinas/jsgrid
10068086
<NME> view.empty.js <BEF> ADDFILE <MSG> added some tests for view.empty (closes #10) <DFF> @@ -0,0 +1,42 @@ + +buster.testCase('View#empty()', { + + "Should run destroy on each child": function() { + var Apple = helpers.Views.Apple; + var list = new helpers.Views.List(); + var apple1 = new Apple(); + var apple2 = new Apple(); + var destroy1 = this.spy(apple1, 'destroy'); + var destroy2 = this.spy(apple2, 'destroy'); + + list + .add(apple1) + .add(apple2) + .render() + .setup(); + + list.empty(); + + assert.isTrue(destroy1.calledOnce); + assert.isTrue(destroy2.calledOnce); + }, + + "Should remove elements from the DOM": function() { + var Apple = helpers.Views.Apple; + var list = new helpers.Views.List(); + var apple1 = new Apple(); + var apple2 = new Apple(); + + list + .add(apple1) + .add(apple2) + .render() + .inject(helpers.sandbox) + .setup(); + + list.empty(); + + assert.isFalse(apple1.inDOM()); + assert.isFalse(apple2.inDOM()); + } +}); \ No newline at end of file
42
added some tests for view.empty (closes #10)
0
.js
empty
mit
ftlabs/fruitmachine
10068087
<NME> README.md <BEF> # LoadJS <img src="https://www.muicss.com/static/images/loadjs.svg" width="250px"> LoadJS is a tiny async loader for modern browsers (899 bytes). [![Dependency Status](https://david-dm.org/muicss/loadjs.svg)](https://david-dm.org/muicss/loadjs) [![devDependency Status](https://david-dm.org/muicss/loadjs/dev-status.svg)](https://david-dm.org/muicss/loadjs?type=dev) [![CDNJS](https://img.shields.io/cdnjs/v/loadjs.svg)](https://cdnjs.com/libraries/loadjs) ## Introduction LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript, CSS and image files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.min.js) in your &lt;html&gt; (possibly in the &lt;head&gt; tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload. LoadJS is based on the excellent [$script](https://github.com/ded/script.js) library by [Dustin Diaz](https://github.com/ded). We kept the behavior of the library the same but we re-wrote the code from scratch to add support for success/error callbacks and to optimize the library for modern browsers. LoadJS is 899 bytes (minified + gzipped). Here's an example of what you can do with LoadJS: ```html <script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script> <script> // define a dependency bundle and execute code when it loads loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); </script> ``` You can also use more advanced syntax for more options: ```html <script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script> <script> // define a dependency bundle with advanced options loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { before: function(path, scriptEl) { /* execute code before fetch */ }, async: true, // load files synchronously or asynchronously (default: true) numRetries: 3 // see caveats about using numRetries with async:false (default: 0), returnPromise: false // return Promise object (default: false) }); loadjs.ready('foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(depsNotFound) { /* foobar bundle load failed */ }, }); </script> ``` The latest version of LoadJS can be found in the `dist/` directory in this repository: * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js) (for development) * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js) (for production) It's also available from these public CDNs: * UNPKG * [https://unpkg.com/[email protected]/dist/loadjs.js](https://unpkg.com/[email protected]/dist/loadjs.js) (for development) * [https://unpkg.com/[email protected]/dist/loadjs.min.js](https://unpkg.com/[email protected]/dist/loadjs.min.js) (for production) * CDNJS * [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js) (for development) * [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js) (for production) You can also use it as a CJS or AMD module: ```bash $ npm install --save loadjs ``` ```javascript var loadjs = require('loadjs'); loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); ``` ## Browser Support * IE9+ (`async: false` support only works in IE10+) * Opera 12+ * Safari 5+ * Chrome * Firefox * iOS 6+ * Android 4.4+ LoadJS also detects script load failures from AdBlock Plus and Ghostery in: * Safari * Chrome 1. Fetch JavaScript and CSS files ```javascript loadjs(['/path/to/foo.css', '/path/to/bar.js'], { success: function() { /* foo.css and bar.js loaded */ } }); ``` 1. Add a bundle id ``` 1. Fetch files in parallel and load them asynchronously ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], function() { /* foo.js and bar.js loaded */ }); ``` 1. Fetch JavaScript, CSS and image files ```javascript loadjs(['/path/to/foo.css', '/path/to/bar.png', 'path/to/thunk.js'], function() { /* foo.css, bar.png and thunk.js loaded */ }); ``` 1. Force treat file as CSS stylesheet ```javascript loadjs(['css!/path/to/cssfile.custom'], function() { /* cssfile.custom loaded as stylesheet */ }); ``` 1. Force treat file as image ```javascript loadjs(['img!/path/to/image.custom'], function() { /* image.custom loaded */ }); ``` 1. Add a bundle id ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }); ``` 1. Use .ready() to define bundles and callbacks separately ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); ``` 1. Use multiple bundles in .ready() dependency lists ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs(['/path/to/bar1.js', '/path/to/bar2.js'], 'bar'); loadjs.ready(['foo', 'bar'], function() { /* foo.js & bar1.js & bar2.js loaded */ }); ``` 1. Chain .ready() together ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs .ready('foo', function() { /* foo.js loaded */ }) .ready('bar', function() { /* bar.js loaded */ }); ``` 1. Use Promises to register callbacks ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], {returnPromise: true}) .then(function() { /* foo.js & bar.js loaded */ }) .catch(function(pathsNotFound) { /* at least one didn't load */ }); ``` 1. Check if bundle has already been defined ```javascript if (!loadjs.isDefined('foobar')) { loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }); } ``` 1. Fetch files in parallel and load them in series ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() { /* foo.js and bar.js loaded in series */ }, async: false }); ``` 1. Add an error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ } }); ``` 1. Retry files before calling the error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ }, numRetries: 3 }); // NOTE: Using `numRetries` with `async: false` can cause files to load out-of-sync on retries ``` 1. Execute a callback before script tags are embedded ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { /* called for each script node before being embedded */ if (path === '/path/to/foo.js') scriptEl.crossOrigin = true; } }); ``` 1. Bypass LoadJS default DOM insertion mechanism (DOM `<head>`) ```javascript loadjs(['/path/to/foo.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { document.body.appendChild(scriptEl); /* return `false` to bypass default DOM insertion mechanism */ return false; } }); ``` 1. Use bundle ids in error callback ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk'); // wait for multiple depdendencies loadjs.ready(['foo', 'bar', 'thunk'], { success: function() { // foo.js & bar.js & thunkor.js & thunky.js loaded }, error: function(depsNotFound) { if (depsNotFound.indexOf('foo') > -1) {}; // foo failed if (depsNotFound.indexOf('bar') > -1) {}; // bar failed if (depsNotFound.indexOf('thunk') > -1) {}; // thunk failed } }); ``` 1. Use .done() for more control ```javascript loadjs.ready(['dependency1', 'dependency2'], function() { /* run code after dependencies have been met */ }); function fn1() { loadjs.done('dependency1'); } function fn2() { loadjs.done('dependency2'); } ``` 1. Reset dependency trackers ```javascript loadjs.reset(); ``` 1. Implement a require-like dependency manager ```javascript var bundles = { 'bundleA': ['/file1.js', '/file2.js'], 'bundleB': ['/file3.js', '/file4.js'] }; function require(bundleIds, callbackFn) { bundleIds.forEach(function(bundleId) { if (!loadjs.isDefined(bundleId)) loadjs(bundles[bundleId], bundleId); }); loadjs.ready(bundleIds, callbackFn); } require(['bundleA'], function() { /* bundleA loaded */ }); require(['bundleB'], function() { /* bundleB loaded */ }); require(['bundleA', 'bundleB'], function() { /* bundleA and bundleB loaded */ }); ``` ## Directory structure <pre> loadjs/ ├── dist │   ├── loadjs.js │   ├── loadjs.min.js │   └── loadjs.umd.js ├── examples ├── gulpfile.js ├── LICENSE.txt ├── package.json ├── README.md ├── src │   └── loadjs.js ├── test └── umd-templates </pre> ## Development Quickstart 1. Install dependencies * [nodejs](http://nodejs.org/) * [npm](https://www.npmjs.org/) * http-server (via npm) 1. Clone repository ```bash $ git clone [email protected]:muicss/loadjs.git $ cd loadjs ``` 1. Install node dependencies using npm ```bash $ npm install ``` 1. Build examples ```bash $ npm run build-examples ``` To view the examples you can use any static file server. To use the `nodejs` http-server module: ```bash $ npm install http-server $ npm run http-server -- -p 3000 ``` Then visit [http://localhost:3000/examples](http://localhost:3000/examples) 1. Build distribution files ```bash $ npm run build-dist ``` The files will be located in the `dist` directory. 1. Run tests To run the browser tests first build the `loadjs` library: ```bash $ npm run build-tests ``` Then visit [http://localhost:3000/test](http://localhost:3000/test) 1. Build all files ```bash $ npm run build-all ``` <MSG> Update README.md <DFF> @@ -93,11 +93,11 @@ Note: LoadJS treats empty CSS files as load failures (as a workaround for the la 1. Fetch JavaScript and CSS files - ```javascript - loadjs(['/path/to/foo.css', '/path/to/bar.js'], { - success: function() { /* foo.css and bar.js loaded */ } - }); - ``` + ```javascript + loadjs(['/path/to/foo.css', '/path/to/bar.js'], { + success: function() { /* foo.css and bar.js loaded */ } + }); + ``` 1. Add a bundle id
5
Update README.md
5
.md
md
mit
muicss/loadjs
10068088
<NME> README.md <BEF> # LoadJS <img src="https://www.muicss.com/static/images/loadjs.svg" width="250px"> LoadJS is a tiny async loader for modern browsers (899 bytes). [![Dependency Status](https://david-dm.org/muicss/loadjs.svg)](https://david-dm.org/muicss/loadjs) [![devDependency Status](https://david-dm.org/muicss/loadjs/dev-status.svg)](https://david-dm.org/muicss/loadjs?type=dev) [![CDNJS](https://img.shields.io/cdnjs/v/loadjs.svg)](https://cdnjs.com/libraries/loadjs) ## Introduction LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript, CSS and image files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.min.js) in your &lt;html&gt; (possibly in the &lt;head&gt; tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload. LoadJS is based on the excellent [$script](https://github.com/ded/script.js) library by [Dustin Diaz](https://github.com/ded). We kept the behavior of the library the same but we re-wrote the code from scratch to add support for success/error callbacks and to optimize the library for modern browsers. LoadJS is 899 bytes (minified + gzipped). Here's an example of what you can do with LoadJS: ```html <script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script> <script> // define a dependency bundle and execute code when it loads loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); </script> ``` You can also use more advanced syntax for more options: ```html <script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script> <script> // define a dependency bundle with advanced options loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { before: function(path, scriptEl) { /* execute code before fetch */ }, async: true, // load files synchronously or asynchronously (default: true) numRetries: 3 // see caveats about using numRetries with async:false (default: 0), returnPromise: false // return Promise object (default: false) }); loadjs.ready('foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(depsNotFound) { /* foobar bundle load failed */ }, }); </script> ``` The latest version of LoadJS can be found in the `dist/` directory in this repository: * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js) (for development) * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js) (for production) It's also available from these public CDNs: * UNPKG * [https://unpkg.com/[email protected]/dist/loadjs.js](https://unpkg.com/[email protected]/dist/loadjs.js) (for development) * [https://unpkg.com/[email protected]/dist/loadjs.min.js](https://unpkg.com/[email protected]/dist/loadjs.min.js) (for production) * CDNJS * [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js) (for development) * [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js) (for production) You can also use it as a CJS or AMD module: ```bash $ npm install --save loadjs ``` ```javascript var loadjs = require('loadjs'); loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); ``` ## Browser Support * IE9+ (`async: false` support only works in IE10+) * Opera 12+ * Safari 5+ * Chrome * Firefox * iOS 6+ * Android 4.4+ LoadJS also detects script load failures from AdBlock Plus and Ghostery in: * Safari * Chrome 1. Fetch JavaScript and CSS files ```javascript loadjs(['/path/to/foo.css', '/path/to/bar.js'], { success: function() { /* foo.css and bar.js loaded */ } }); ``` 1. Add a bundle id ``` 1. Fetch files in parallel and load them asynchronously ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], function() { /* foo.js and bar.js loaded */ }); ``` 1. Fetch JavaScript, CSS and image files ```javascript loadjs(['/path/to/foo.css', '/path/to/bar.png', 'path/to/thunk.js'], function() { /* foo.css, bar.png and thunk.js loaded */ }); ``` 1. Force treat file as CSS stylesheet ```javascript loadjs(['css!/path/to/cssfile.custom'], function() { /* cssfile.custom loaded as stylesheet */ }); ``` 1. Force treat file as image ```javascript loadjs(['img!/path/to/image.custom'], function() { /* image.custom loaded */ }); ``` 1. Add a bundle id ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }); ``` 1. Use .ready() to define bundles and callbacks separately ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); ``` 1. Use multiple bundles in .ready() dependency lists ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs(['/path/to/bar1.js', '/path/to/bar2.js'], 'bar'); loadjs.ready(['foo', 'bar'], function() { /* foo.js & bar1.js & bar2.js loaded */ }); ``` 1. Chain .ready() together ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs .ready('foo', function() { /* foo.js loaded */ }) .ready('bar', function() { /* bar.js loaded */ }); ``` 1. Use Promises to register callbacks ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], {returnPromise: true}) .then(function() { /* foo.js & bar.js loaded */ }) .catch(function(pathsNotFound) { /* at least one didn't load */ }); ``` 1. Check if bundle has already been defined ```javascript if (!loadjs.isDefined('foobar')) { loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }); } ``` 1. Fetch files in parallel and load them in series ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() { /* foo.js and bar.js loaded in series */ }, async: false }); ``` 1. Add an error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ } }); ``` 1. Retry files before calling the error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ }, numRetries: 3 }); // NOTE: Using `numRetries` with `async: false` can cause files to load out-of-sync on retries ``` 1. Execute a callback before script tags are embedded ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { /* called for each script node before being embedded */ if (path === '/path/to/foo.js') scriptEl.crossOrigin = true; } }); ``` 1. Bypass LoadJS default DOM insertion mechanism (DOM `<head>`) ```javascript loadjs(['/path/to/foo.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { document.body.appendChild(scriptEl); /* return `false` to bypass default DOM insertion mechanism */ return false; } }); ``` 1. Use bundle ids in error callback ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk'); // wait for multiple depdendencies loadjs.ready(['foo', 'bar', 'thunk'], { success: function() { // foo.js & bar.js & thunkor.js & thunky.js loaded }, error: function(depsNotFound) { if (depsNotFound.indexOf('foo') > -1) {}; // foo failed if (depsNotFound.indexOf('bar') > -1) {}; // bar failed if (depsNotFound.indexOf('thunk') > -1) {}; // thunk failed } }); ``` 1. Use .done() for more control ```javascript loadjs.ready(['dependency1', 'dependency2'], function() { /* run code after dependencies have been met */ }); function fn1() { loadjs.done('dependency1'); } function fn2() { loadjs.done('dependency2'); } ``` 1. Reset dependency trackers ```javascript loadjs.reset(); ``` 1. Implement a require-like dependency manager ```javascript var bundles = { 'bundleA': ['/file1.js', '/file2.js'], 'bundleB': ['/file3.js', '/file4.js'] }; function require(bundleIds, callbackFn) { bundleIds.forEach(function(bundleId) { if (!loadjs.isDefined(bundleId)) loadjs(bundles[bundleId], bundleId); }); loadjs.ready(bundleIds, callbackFn); } require(['bundleA'], function() { /* bundleA loaded */ }); require(['bundleB'], function() { /* bundleB loaded */ }); require(['bundleA', 'bundleB'], function() { /* bundleA and bundleB loaded */ }); ``` ## Directory structure <pre> loadjs/ ├── dist │   ├── loadjs.js │   ├── loadjs.min.js │   └── loadjs.umd.js ├── examples ├── gulpfile.js ├── LICENSE.txt ├── package.json ├── README.md ├── src │   └── loadjs.js ├── test └── umd-templates </pre> ## Development Quickstart 1. Install dependencies * [nodejs](http://nodejs.org/) * [npm](https://www.npmjs.org/) * http-server (via npm) 1. Clone repository ```bash $ git clone [email protected]:muicss/loadjs.git $ cd loadjs ``` 1. Install node dependencies using npm ```bash $ npm install ``` 1. Build examples ```bash $ npm run build-examples ``` To view the examples you can use any static file server. To use the `nodejs` http-server module: ```bash $ npm install http-server $ npm run http-server -- -p 3000 ``` Then visit [http://localhost:3000/examples](http://localhost:3000/examples) 1. Build distribution files ```bash $ npm run build-dist ``` The files will be located in the `dist` directory. 1. Run tests To run the browser tests first build the `loadjs` library: ```bash $ npm run build-tests ``` Then visit [http://localhost:3000/test](http://localhost:3000/test) 1. Build all files ```bash $ npm run build-all ``` <MSG> Update README.md <DFF> @@ -93,11 +93,11 @@ Note: LoadJS treats empty CSS files as load failures (as a workaround for the la 1. Fetch JavaScript and CSS files - ```javascript - loadjs(['/path/to/foo.css', '/path/to/bar.js'], { - success: function() { /* foo.css and bar.js loaded */ } - }); - ``` + ```javascript + loadjs(['/path/to/foo.css', '/path/to/bar.js'], { + success: function() { /* foo.css and bar.js loaded */ } + }); + ``` 1. Add a bundle id
5
Update README.md
5
.md
md
mit
muicss/loadjs
10068089
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); } } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> TextArea always installs search panel. <DFF> @@ -27,6 +27,7 @@ using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; +using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; @@ -114,6 +115,8 @@ namespace AvaloniaEdit.Editing { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); + + SearchPanel.Install(this); } } @@ -1025,7 +1028,7 @@ namespace AvaloniaEdit.Editing _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); - if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) + if (TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); }
4
TextArea always installs search panel.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068090
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); } } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> TextArea always installs search panel. <DFF> @@ -27,6 +27,7 @@ using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; +using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; @@ -114,6 +115,8 @@ namespace AvaloniaEdit.Editing { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); + + SearchPanel.Install(this); } } @@ -1025,7 +1028,7 @@ namespace AvaloniaEdit.Editing _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); - if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) + if (TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); }
4
TextArea always installs search panel.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068091
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); } } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> TextArea always installs search panel. <DFF> @@ -27,6 +27,7 @@ using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; +using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; @@ -114,6 +115,8 @@ namespace AvaloniaEdit.Editing { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); + + SearchPanel.Install(this); } } @@ -1025,7 +1028,7 @@ namespace AvaloniaEdit.Editing _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); - if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) + if (TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); }
4
TextArea always installs search panel.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068092
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); } } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> TextArea always installs search panel. <DFF> @@ -27,6 +27,7 @@ using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; +using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; @@ -114,6 +115,8 @@ namespace AvaloniaEdit.Editing { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); + + SearchPanel.Install(this); } } @@ -1025,7 +1028,7 @@ namespace AvaloniaEdit.Editing _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); - if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) + if (TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); }
4
TextArea always installs search panel.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068093
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); } } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> TextArea always installs search panel. <DFF> @@ -27,6 +27,7 @@ using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; +using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; @@ -114,6 +115,8 @@ namespace AvaloniaEdit.Editing { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); + + SearchPanel.Install(this); } } @@ -1025,7 +1028,7 @@ namespace AvaloniaEdit.Editing _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); - if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) + if (TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); }
4
TextArea always installs search panel.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068094
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); } } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> TextArea always installs search panel. <DFF> @@ -27,6 +27,7 @@ using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; +using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; @@ -114,6 +115,8 @@ namespace AvaloniaEdit.Editing { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); + + SearchPanel.Install(this); } } @@ -1025,7 +1028,7 @@ namespace AvaloniaEdit.Editing _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); - if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) + if (TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); }
4
TextArea always installs search panel.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068095
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); } } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> TextArea always installs search panel. <DFF> @@ -27,6 +27,7 @@ using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; +using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; @@ -114,6 +115,8 @@ namespace AvaloniaEdit.Editing { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); + + SearchPanel.Install(this); } } @@ -1025,7 +1028,7 @@ namespace AvaloniaEdit.Editing _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); - if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) + if (TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); }
4
TextArea always installs search panel.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068096
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); } } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> TextArea always installs search panel. <DFF> @@ -27,6 +27,7 @@ using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; +using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; @@ -114,6 +115,8 @@ namespace AvaloniaEdit.Editing { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); + + SearchPanel.Install(this); } } @@ -1025,7 +1028,7 @@ namespace AvaloniaEdit.Editing _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); - if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) + if (TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); }
4
TextArea always installs search panel.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068097
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); } } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> TextArea always installs search panel. <DFF> @@ -27,6 +27,7 @@ using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; +using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; @@ -114,6 +115,8 @@ namespace AvaloniaEdit.Editing { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); + + SearchPanel.Install(this); } } @@ -1025,7 +1028,7 @@ namespace AvaloniaEdit.Editing _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); - if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) + if (TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); }
4
TextArea always installs search panel.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068098
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); } } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> TextArea always installs search panel. <DFF> @@ -27,6 +27,7 @@ using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; +using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; @@ -114,6 +115,8 @@ namespace AvaloniaEdit.Editing { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); + + SearchPanel.Install(this); } } @@ -1025,7 +1028,7 @@ namespace AvaloniaEdit.Editing _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); - if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) + if (TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); }
4
TextArea always installs search panel.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068099
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); } } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> TextArea always installs search panel. <DFF> @@ -27,6 +27,7 @@ using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; +using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; @@ -114,6 +115,8 @@ namespace AvaloniaEdit.Editing { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); + + SearchPanel.Install(this); } } @@ -1025,7 +1028,7 @@ namespace AvaloniaEdit.Editing _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); - if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) + if (TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); }
4
TextArea always installs search panel.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068100
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); } } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> TextArea always installs search panel. <DFF> @@ -27,6 +27,7 @@ using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; +using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; @@ -114,6 +115,8 @@ namespace AvaloniaEdit.Editing { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); + + SearchPanel.Install(this); } } @@ -1025,7 +1028,7 @@ namespace AvaloniaEdit.Editing _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); - if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) + if (TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); }
4
TextArea always installs search panel.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068101
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); } } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> TextArea always installs search panel. <DFF> @@ -27,6 +27,7 @@ using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; +using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; @@ -114,6 +115,8 @@ namespace AvaloniaEdit.Editing { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); + + SearchPanel.Install(this); } } @@ -1025,7 +1028,7 @@ namespace AvaloniaEdit.Editing _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); - if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) + if (TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); }
4
TextArea always installs search panel.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068102
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); } } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> TextArea always installs search panel. <DFF> @@ -27,6 +27,7 @@ using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; +using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; @@ -114,6 +115,8 @@ namespace AvaloniaEdit.Editing { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); + + SearchPanel.Install(this); } } @@ -1025,7 +1028,7 @@ namespace AvaloniaEdit.Editing _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); - if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) + if (TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); }
4
TextArea always installs search panel.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068103
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); } } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> TextArea always installs search panel. <DFF> @@ -27,6 +27,7 @@ using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; +using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; @@ -114,6 +115,8 @@ namespace AvaloniaEdit.Editing { contentPresenter.Content = TextView; ((ISetLogicalParent)TextView).SetParent(this); + + SearchPanel.Install(this); } } @@ -1025,7 +1028,7 @@ namespace AvaloniaEdit.Editing _viewPort = new Size(finalSize.Width, finalSize.Height / TextView.DefaultLineHeight); _extent = new Size(finalSize.Width, LogicalScrollSize); - if(TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) + if (TextView.SetScrollData(new Size(_viewPort.Width, _viewPort.Height * TextView.DefaultLineHeight), _extent)) { TextView.Redraw(); }
4
TextArea always installs search panel.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068104
<NME> RELEASE.md <BEF> # Release Instructions 1. Build packages ```bash $ npm run build-all ``` 1. Add release notes to CHANGELOG.md 1. Change version number in package.json 1. Change version number in bower.json 1. Update CDN urls in README.md 1. Commit changes and tag code ```bash $ git add . --all $ git commit -a -m "bumped version number" $ git push origin master 1. Push changes to NPM ```bash $ cd packages/npm $ npm publish ``` ```bash $ npm publish ``` <MSG> fixed release instructions <DFF> @@ -23,6 +23,5 @@ 1. Push changes to NPM ```bash - $ cd packages/npm $ npm publish ```
0
fixed release instructions
1
.md
md
mit
muicss/loadjs
10068105
<NME> RELEASE.md <BEF> # Release Instructions 1. Build packages ```bash $ npm run build-all ``` 1. Add release notes to CHANGELOG.md 1. Change version number in package.json 1. Change version number in bower.json 1. Update CDN urls in README.md 1. Commit changes and tag code ```bash $ git add . --all $ git commit -a -m "bumped version number" $ git push origin master 1. Push changes to NPM ```bash $ cd packages/npm $ npm publish ``` ```bash $ npm publish ``` <MSG> fixed release instructions <DFF> @@ -23,6 +23,5 @@ 1. Push changes to NPM ```bash - $ cd packages/npm $ npm publish ```
0
fixed release instructions
1
.md
md
mit
muicss/loadjs
10068106
<NME> module.module.js <BEF> buster.testCase('View#module()', { setUp: function() { var layout = new Layout({}); var apple = new Apple({ slot: 1 }); var orange = new Orange({ slot: 2 }); var layout = new Layout({}); var apple = new Apple({ slot: 1 }); var orange = new Orange({ slot: 2 }); var pear = new Pear({ slot: 3 }); layout .add(apple) this.view = layout; }, "Should return module type if no arguments given": function() { assert.equals(this.view.module(), 'layout'); }, expect(viewToTest.module()).toBe('layout'); }); test("Should return the first child module with the specified type.", function() { var child = viewToTest.module('pear'); expect(child).toBe(viewToTest.children[2]); }); test("If there is more than one child of this module type, only the first is returned.", function() { viewToTest .add({ module: 'apple' }); var child = viewToTest.module('apple'); var firstChild = viewToTest.children[0]; var lastChild = viewToTest.children[viewToTest.children.length-1]; expect(child).toBe(firstChild); expect(child).not.toEqual(lastChild); }); test("Should return the module name if defined with the name key", function() { assert.equals(henry.module(), 'henry'); assert.equals(henry.name, 'henry'); } }); expect(henry.name).toBe('henry'); }); test("Should walk down the fruitmachine tree, recursively", function() { var Elizabeth = fruitmachine.define({ name: 'elizabeth' }); var elizabeth = new Elizabeth(); viewToTest.module('apple').add(elizabeth); var elizabethInstance = viewToTest.module('elizabeth'); expect(elizabethInstance.module()).toBe('elizabeth'); expect(elizabethInstance.name).toBe('elizabeth'); }); test("Regression Test: Should still recurse even if the root view used to have a module of the same type", function() { var pear = viewToTest.module('pear').remove(); viewToTest.module('apple').add(pear); var pearInstance = viewToTest.module('pear'); expect(pearInstance.module()).toBe('pear'); expect(pearInstance.name).toBe('pear'); }); }); <MSG> Fix an indentation issue <DFF> @@ -1,6 +1,5 @@ - buster.testCase('View#module()', { - setUp: function() { + setUp: function() { var layout = new Layout({}); var apple = new Apple({ slot: 1 }); var orange = new Orange({ slot: 2 }); @@ -14,7 +13,7 @@ buster.testCase('View#module()', { this.view = layout; }, - "Should return module type if no arguments given": function() { + "Should return module type if no arguments given": function() { assert.equals(this.view.module(), 'layout'); }, @@ -43,4 +42,4 @@ buster.testCase('View#module()', { assert.equals(henry.module(), 'henry'); assert.equals(henry.name, 'henry'); } -}); \ No newline at end of file +});
3
Fix an indentation issue
4
.js
module
mit
ftlabs/fruitmachine
10068107
<NME> build.cake <BEF> ADDFILE <MSG> add buildscript (for dans fork to test build) <DFF> @@ -0,0 +1,142 @@ + +var target = Argument("target", "Default"); +var platform = Argument("platform", "AnyCPU"); +var configuration = Argument("configuration", "Release"); + +var version = "dev-0.20"; + +var editbin = @"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\bin\HostX86\x86\editbin.exe"; + +var artifactsDir = (DirectoryPath)Directory("./artifacts"); +var zipRootDir = artifactsDir.Combine("zip"); + +var fileZipSuffix = ".zip"; + +var buildDirs = GetDirectories("./src/AvalonStudio/**/bin/**") + + GetDirectories("./src/AvalonStudio/**/obj/**") + + GetDirectories("./artifacts/**/zip/**"); + +var netCoreAppsRoot= "./src/"; +var netCoreApps = new string[] { "AvaloniaEdit.Demo.NetCore" }; +var netCoreProjects = netCoreApps.Select(name => + new { + Path = string.Format("{0}/{1}", netCoreAppsRoot, name), + Name = name, + Framework = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='TargetFramework']/text()"), + Runtimes = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='RuntimeIdentifiers']/text()").Split(';') + }).ToList(); + +if (BuildSystem.AppVeyor.IsRunningOnAppVeyor) +{ + if (BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name)) + version = BuildSystem.AppVeyor.Environment.Repository.Tag.Name; + else + version += "-build" + EnvironmentVariable("APPVEYOR_BUILD_NUMBER"); +} + +var MainRepo = "danwalmsley/AvaloniaEdit"; +var MasterBranch = "master"; +var ReleasePlatform = "Any CPU"; +var ReleaseConfiguration = "Release"; + +var isPlatformAnyCPU = StringComparer.OrdinalIgnoreCase.Equals(platform, "Any CPU"); +var isPlatformX86 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x86"); +var isPlatformX64 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x64"); +var isLocalBuild = BuildSystem.IsLocalBuild; +var isRunningOnUnix = IsRunningOnUnix(); +var isRunningOnWindows = IsRunningOnWindows(); +var isRunningOnAppVeyor = BuildSystem.AppVeyor.IsRunningOnAppVeyor; +var isPullRequest = BuildSystem.AppVeyor.Environment.PullRequest.IsPullRequest; +var isMainRepo = StringComparer.OrdinalIgnoreCase.Equals(MainRepo, BuildSystem.AppVeyor.Environment.Repository.Name); +var isMasterBranch = StringComparer.OrdinalIgnoreCase.Equals(MasterBranch, BuildSystem.AppVeyor.Environment.Repository.Branch); +var isTagged = BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag + && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name); +var isReleasable = StringComparer.OrdinalIgnoreCase.Equals(ReleasePlatform, platform) + && StringComparer.OrdinalIgnoreCase.Equals(ReleaseConfiguration, configuration); +var isMyGetRelease = !isTagged && isReleasable; +var isNuGetRelease = isTagged && isReleasable; + +Task("Clean") +.Does(()=>{ + CleanDirectories(buildDirs); +}); + +Task("Restore-NetCore") + .IsDependentOn("Clean") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + DotNetCoreRestore(project.Path); + } +}); + +Task("Build-NetCore") + .IsDependentOn("Restore-NetCore") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + Information("Building: {0}", project.Name); + DotNetCoreBuild(project.Path, new DotNetCoreBuildSettings { + Configuration = configuration + }); + } +}); + +Task("Publish-NetCore") + .IsDependentOn("Restore-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Information("Publishing: {0}, runtime: {1}", project.Name, runtime); + DotNetCorePublish(project.Path, new DotNetCorePublishSettings { + Framework = project.Framework, + Configuration = configuration, + Runtime = runtime, + OutputDirectory = outputDir.FullPath + }); + + if (IsRunningOnWindows() && (runtime == "win7-x86" || runtime == "win7-x64")) + { + Information("Patching executable subsystem for: {0}, runtime: {1}", project.Name, runtime); + var targetExe = outputDir.CombineWithFilePath(project.Name + ".exe"); + var exitCodeWithArgument = StartProcess(editbin, new ProcessSettings { + Arguments = "/subsystem:windows " + targetExe.FullPath + }); + Information("The editbin command exit code: {0}", exitCodeWithArgument); + } + } + } +}); + +Task("Zip-NetCore") + .IsDependentOn("Publish-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Zip(outputDir.FullPath, zipRootDir.CombineWithFilePath(project.Name + "-" + runtime + fileZipSuffix), + GetFiles(outputDir.FullPath + "/*.*")); + } + } +}); + +Task("Default") + .IsDependentOn("Restore-NetCore") + .IsDependentOn("Build-NetCore") + .IsDependentOn("Publish-NetCore") + .IsDependentOn("Zip-NetCore"); + +RunTarget(target);
142
add buildscript (for dans fork to test build)
0
.cake
cake
mit
AvaloniaUI/AvaloniaEdit
10068108
<NME> build.cake <BEF> ADDFILE <MSG> add buildscript (for dans fork to test build) <DFF> @@ -0,0 +1,142 @@ + +var target = Argument("target", "Default"); +var platform = Argument("platform", "AnyCPU"); +var configuration = Argument("configuration", "Release"); + +var version = "dev-0.20"; + +var editbin = @"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\bin\HostX86\x86\editbin.exe"; + +var artifactsDir = (DirectoryPath)Directory("./artifacts"); +var zipRootDir = artifactsDir.Combine("zip"); + +var fileZipSuffix = ".zip"; + +var buildDirs = GetDirectories("./src/AvalonStudio/**/bin/**") + + GetDirectories("./src/AvalonStudio/**/obj/**") + + GetDirectories("./artifacts/**/zip/**"); + +var netCoreAppsRoot= "./src/"; +var netCoreApps = new string[] { "AvaloniaEdit.Demo.NetCore" }; +var netCoreProjects = netCoreApps.Select(name => + new { + Path = string.Format("{0}/{1}", netCoreAppsRoot, name), + Name = name, + Framework = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='TargetFramework']/text()"), + Runtimes = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='RuntimeIdentifiers']/text()").Split(';') + }).ToList(); + +if (BuildSystem.AppVeyor.IsRunningOnAppVeyor) +{ + if (BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name)) + version = BuildSystem.AppVeyor.Environment.Repository.Tag.Name; + else + version += "-build" + EnvironmentVariable("APPVEYOR_BUILD_NUMBER"); +} + +var MainRepo = "danwalmsley/AvaloniaEdit"; +var MasterBranch = "master"; +var ReleasePlatform = "Any CPU"; +var ReleaseConfiguration = "Release"; + +var isPlatformAnyCPU = StringComparer.OrdinalIgnoreCase.Equals(platform, "Any CPU"); +var isPlatformX86 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x86"); +var isPlatformX64 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x64"); +var isLocalBuild = BuildSystem.IsLocalBuild; +var isRunningOnUnix = IsRunningOnUnix(); +var isRunningOnWindows = IsRunningOnWindows(); +var isRunningOnAppVeyor = BuildSystem.AppVeyor.IsRunningOnAppVeyor; +var isPullRequest = BuildSystem.AppVeyor.Environment.PullRequest.IsPullRequest; +var isMainRepo = StringComparer.OrdinalIgnoreCase.Equals(MainRepo, BuildSystem.AppVeyor.Environment.Repository.Name); +var isMasterBranch = StringComparer.OrdinalIgnoreCase.Equals(MasterBranch, BuildSystem.AppVeyor.Environment.Repository.Branch); +var isTagged = BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag + && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name); +var isReleasable = StringComparer.OrdinalIgnoreCase.Equals(ReleasePlatform, platform) + && StringComparer.OrdinalIgnoreCase.Equals(ReleaseConfiguration, configuration); +var isMyGetRelease = !isTagged && isReleasable; +var isNuGetRelease = isTagged && isReleasable; + +Task("Clean") +.Does(()=>{ + CleanDirectories(buildDirs); +}); + +Task("Restore-NetCore") + .IsDependentOn("Clean") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + DotNetCoreRestore(project.Path); + } +}); + +Task("Build-NetCore") + .IsDependentOn("Restore-NetCore") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + Information("Building: {0}", project.Name); + DotNetCoreBuild(project.Path, new DotNetCoreBuildSettings { + Configuration = configuration + }); + } +}); + +Task("Publish-NetCore") + .IsDependentOn("Restore-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Information("Publishing: {0}, runtime: {1}", project.Name, runtime); + DotNetCorePublish(project.Path, new DotNetCorePublishSettings { + Framework = project.Framework, + Configuration = configuration, + Runtime = runtime, + OutputDirectory = outputDir.FullPath + }); + + if (IsRunningOnWindows() && (runtime == "win7-x86" || runtime == "win7-x64")) + { + Information("Patching executable subsystem for: {0}, runtime: {1}", project.Name, runtime); + var targetExe = outputDir.CombineWithFilePath(project.Name + ".exe"); + var exitCodeWithArgument = StartProcess(editbin, new ProcessSettings { + Arguments = "/subsystem:windows " + targetExe.FullPath + }); + Information("The editbin command exit code: {0}", exitCodeWithArgument); + } + } + } +}); + +Task("Zip-NetCore") + .IsDependentOn("Publish-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Zip(outputDir.FullPath, zipRootDir.CombineWithFilePath(project.Name + "-" + runtime + fileZipSuffix), + GetFiles(outputDir.FullPath + "/*.*")); + } + } +}); + +Task("Default") + .IsDependentOn("Restore-NetCore") + .IsDependentOn("Build-NetCore") + .IsDependentOn("Publish-NetCore") + .IsDependentOn("Zip-NetCore"); + +RunTarget(target);
142
add buildscript (for dans fork to test build)
0
.cake
cake
mit
AvaloniaUI/AvaloniaEdit
10068109
<NME> build.cake <BEF> ADDFILE <MSG> add buildscript (for dans fork to test build) <DFF> @@ -0,0 +1,142 @@ + +var target = Argument("target", "Default"); +var platform = Argument("platform", "AnyCPU"); +var configuration = Argument("configuration", "Release"); + +var version = "dev-0.20"; + +var editbin = @"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\bin\HostX86\x86\editbin.exe"; + +var artifactsDir = (DirectoryPath)Directory("./artifacts"); +var zipRootDir = artifactsDir.Combine("zip"); + +var fileZipSuffix = ".zip"; + +var buildDirs = GetDirectories("./src/AvalonStudio/**/bin/**") + + GetDirectories("./src/AvalonStudio/**/obj/**") + + GetDirectories("./artifacts/**/zip/**"); + +var netCoreAppsRoot= "./src/"; +var netCoreApps = new string[] { "AvaloniaEdit.Demo.NetCore" }; +var netCoreProjects = netCoreApps.Select(name => + new { + Path = string.Format("{0}/{1}", netCoreAppsRoot, name), + Name = name, + Framework = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='TargetFramework']/text()"), + Runtimes = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='RuntimeIdentifiers']/text()").Split(';') + }).ToList(); + +if (BuildSystem.AppVeyor.IsRunningOnAppVeyor) +{ + if (BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name)) + version = BuildSystem.AppVeyor.Environment.Repository.Tag.Name; + else + version += "-build" + EnvironmentVariable("APPVEYOR_BUILD_NUMBER"); +} + +var MainRepo = "danwalmsley/AvaloniaEdit"; +var MasterBranch = "master"; +var ReleasePlatform = "Any CPU"; +var ReleaseConfiguration = "Release"; + +var isPlatformAnyCPU = StringComparer.OrdinalIgnoreCase.Equals(platform, "Any CPU"); +var isPlatformX86 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x86"); +var isPlatformX64 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x64"); +var isLocalBuild = BuildSystem.IsLocalBuild; +var isRunningOnUnix = IsRunningOnUnix(); +var isRunningOnWindows = IsRunningOnWindows(); +var isRunningOnAppVeyor = BuildSystem.AppVeyor.IsRunningOnAppVeyor; +var isPullRequest = BuildSystem.AppVeyor.Environment.PullRequest.IsPullRequest; +var isMainRepo = StringComparer.OrdinalIgnoreCase.Equals(MainRepo, BuildSystem.AppVeyor.Environment.Repository.Name); +var isMasterBranch = StringComparer.OrdinalIgnoreCase.Equals(MasterBranch, BuildSystem.AppVeyor.Environment.Repository.Branch); +var isTagged = BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag + && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name); +var isReleasable = StringComparer.OrdinalIgnoreCase.Equals(ReleasePlatform, platform) + && StringComparer.OrdinalIgnoreCase.Equals(ReleaseConfiguration, configuration); +var isMyGetRelease = !isTagged && isReleasable; +var isNuGetRelease = isTagged && isReleasable; + +Task("Clean") +.Does(()=>{ + CleanDirectories(buildDirs); +}); + +Task("Restore-NetCore") + .IsDependentOn("Clean") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + DotNetCoreRestore(project.Path); + } +}); + +Task("Build-NetCore") + .IsDependentOn("Restore-NetCore") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + Information("Building: {0}", project.Name); + DotNetCoreBuild(project.Path, new DotNetCoreBuildSettings { + Configuration = configuration + }); + } +}); + +Task("Publish-NetCore") + .IsDependentOn("Restore-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Information("Publishing: {0}, runtime: {1}", project.Name, runtime); + DotNetCorePublish(project.Path, new DotNetCorePublishSettings { + Framework = project.Framework, + Configuration = configuration, + Runtime = runtime, + OutputDirectory = outputDir.FullPath + }); + + if (IsRunningOnWindows() && (runtime == "win7-x86" || runtime == "win7-x64")) + { + Information("Patching executable subsystem for: {0}, runtime: {1}", project.Name, runtime); + var targetExe = outputDir.CombineWithFilePath(project.Name + ".exe"); + var exitCodeWithArgument = StartProcess(editbin, new ProcessSettings { + Arguments = "/subsystem:windows " + targetExe.FullPath + }); + Information("The editbin command exit code: {0}", exitCodeWithArgument); + } + } + } +}); + +Task("Zip-NetCore") + .IsDependentOn("Publish-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Zip(outputDir.FullPath, zipRootDir.CombineWithFilePath(project.Name + "-" + runtime + fileZipSuffix), + GetFiles(outputDir.FullPath + "/*.*")); + } + } +}); + +Task("Default") + .IsDependentOn("Restore-NetCore") + .IsDependentOn("Build-NetCore") + .IsDependentOn("Publish-NetCore") + .IsDependentOn("Zip-NetCore"); + +RunTarget(target);
142
add buildscript (for dans fork to test build)
0
.cake
cake
mit
AvaloniaUI/AvaloniaEdit
10068110
<NME> build.cake <BEF> ADDFILE <MSG> add buildscript (for dans fork to test build) <DFF> @@ -0,0 +1,142 @@ + +var target = Argument("target", "Default"); +var platform = Argument("platform", "AnyCPU"); +var configuration = Argument("configuration", "Release"); + +var version = "dev-0.20"; + +var editbin = @"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\bin\HostX86\x86\editbin.exe"; + +var artifactsDir = (DirectoryPath)Directory("./artifacts"); +var zipRootDir = artifactsDir.Combine("zip"); + +var fileZipSuffix = ".zip"; + +var buildDirs = GetDirectories("./src/AvalonStudio/**/bin/**") + + GetDirectories("./src/AvalonStudio/**/obj/**") + + GetDirectories("./artifacts/**/zip/**"); + +var netCoreAppsRoot= "./src/"; +var netCoreApps = new string[] { "AvaloniaEdit.Demo.NetCore" }; +var netCoreProjects = netCoreApps.Select(name => + new { + Path = string.Format("{0}/{1}", netCoreAppsRoot, name), + Name = name, + Framework = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='TargetFramework']/text()"), + Runtimes = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='RuntimeIdentifiers']/text()").Split(';') + }).ToList(); + +if (BuildSystem.AppVeyor.IsRunningOnAppVeyor) +{ + if (BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name)) + version = BuildSystem.AppVeyor.Environment.Repository.Tag.Name; + else + version += "-build" + EnvironmentVariable("APPVEYOR_BUILD_NUMBER"); +} + +var MainRepo = "danwalmsley/AvaloniaEdit"; +var MasterBranch = "master"; +var ReleasePlatform = "Any CPU"; +var ReleaseConfiguration = "Release"; + +var isPlatformAnyCPU = StringComparer.OrdinalIgnoreCase.Equals(platform, "Any CPU"); +var isPlatformX86 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x86"); +var isPlatformX64 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x64"); +var isLocalBuild = BuildSystem.IsLocalBuild; +var isRunningOnUnix = IsRunningOnUnix(); +var isRunningOnWindows = IsRunningOnWindows(); +var isRunningOnAppVeyor = BuildSystem.AppVeyor.IsRunningOnAppVeyor; +var isPullRequest = BuildSystem.AppVeyor.Environment.PullRequest.IsPullRequest; +var isMainRepo = StringComparer.OrdinalIgnoreCase.Equals(MainRepo, BuildSystem.AppVeyor.Environment.Repository.Name); +var isMasterBranch = StringComparer.OrdinalIgnoreCase.Equals(MasterBranch, BuildSystem.AppVeyor.Environment.Repository.Branch); +var isTagged = BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag + && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name); +var isReleasable = StringComparer.OrdinalIgnoreCase.Equals(ReleasePlatform, platform) + && StringComparer.OrdinalIgnoreCase.Equals(ReleaseConfiguration, configuration); +var isMyGetRelease = !isTagged && isReleasable; +var isNuGetRelease = isTagged && isReleasable; + +Task("Clean") +.Does(()=>{ + CleanDirectories(buildDirs); +}); + +Task("Restore-NetCore") + .IsDependentOn("Clean") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + DotNetCoreRestore(project.Path); + } +}); + +Task("Build-NetCore") + .IsDependentOn("Restore-NetCore") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + Information("Building: {0}", project.Name); + DotNetCoreBuild(project.Path, new DotNetCoreBuildSettings { + Configuration = configuration + }); + } +}); + +Task("Publish-NetCore") + .IsDependentOn("Restore-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Information("Publishing: {0}, runtime: {1}", project.Name, runtime); + DotNetCorePublish(project.Path, new DotNetCorePublishSettings { + Framework = project.Framework, + Configuration = configuration, + Runtime = runtime, + OutputDirectory = outputDir.FullPath + }); + + if (IsRunningOnWindows() && (runtime == "win7-x86" || runtime == "win7-x64")) + { + Information("Patching executable subsystem for: {0}, runtime: {1}", project.Name, runtime); + var targetExe = outputDir.CombineWithFilePath(project.Name + ".exe"); + var exitCodeWithArgument = StartProcess(editbin, new ProcessSettings { + Arguments = "/subsystem:windows " + targetExe.FullPath + }); + Information("The editbin command exit code: {0}", exitCodeWithArgument); + } + } + } +}); + +Task("Zip-NetCore") + .IsDependentOn("Publish-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Zip(outputDir.FullPath, zipRootDir.CombineWithFilePath(project.Name + "-" + runtime + fileZipSuffix), + GetFiles(outputDir.FullPath + "/*.*")); + } + } +}); + +Task("Default") + .IsDependentOn("Restore-NetCore") + .IsDependentOn("Build-NetCore") + .IsDependentOn("Publish-NetCore") + .IsDependentOn("Zip-NetCore"); + +RunTarget(target);
142
add buildscript (for dans fork to test build)
0
.cake
cake
mit
AvaloniaUI/AvaloniaEdit
10068111
<NME> build.cake <BEF> ADDFILE <MSG> add buildscript (for dans fork to test build) <DFF> @@ -0,0 +1,142 @@ + +var target = Argument("target", "Default"); +var platform = Argument("platform", "AnyCPU"); +var configuration = Argument("configuration", "Release"); + +var version = "dev-0.20"; + +var editbin = @"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\bin\HostX86\x86\editbin.exe"; + +var artifactsDir = (DirectoryPath)Directory("./artifacts"); +var zipRootDir = artifactsDir.Combine("zip"); + +var fileZipSuffix = ".zip"; + +var buildDirs = GetDirectories("./src/AvalonStudio/**/bin/**") + + GetDirectories("./src/AvalonStudio/**/obj/**") + + GetDirectories("./artifacts/**/zip/**"); + +var netCoreAppsRoot= "./src/"; +var netCoreApps = new string[] { "AvaloniaEdit.Demo.NetCore" }; +var netCoreProjects = netCoreApps.Select(name => + new { + Path = string.Format("{0}/{1}", netCoreAppsRoot, name), + Name = name, + Framework = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='TargetFramework']/text()"), + Runtimes = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='RuntimeIdentifiers']/text()").Split(';') + }).ToList(); + +if (BuildSystem.AppVeyor.IsRunningOnAppVeyor) +{ + if (BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name)) + version = BuildSystem.AppVeyor.Environment.Repository.Tag.Name; + else + version += "-build" + EnvironmentVariable("APPVEYOR_BUILD_NUMBER"); +} + +var MainRepo = "danwalmsley/AvaloniaEdit"; +var MasterBranch = "master"; +var ReleasePlatform = "Any CPU"; +var ReleaseConfiguration = "Release"; + +var isPlatformAnyCPU = StringComparer.OrdinalIgnoreCase.Equals(platform, "Any CPU"); +var isPlatformX86 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x86"); +var isPlatformX64 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x64"); +var isLocalBuild = BuildSystem.IsLocalBuild; +var isRunningOnUnix = IsRunningOnUnix(); +var isRunningOnWindows = IsRunningOnWindows(); +var isRunningOnAppVeyor = BuildSystem.AppVeyor.IsRunningOnAppVeyor; +var isPullRequest = BuildSystem.AppVeyor.Environment.PullRequest.IsPullRequest; +var isMainRepo = StringComparer.OrdinalIgnoreCase.Equals(MainRepo, BuildSystem.AppVeyor.Environment.Repository.Name); +var isMasterBranch = StringComparer.OrdinalIgnoreCase.Equals(MasterBranch, BuildSystem.AppVeyor.Environment.Repository.Branch); +var isTagged = BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag + && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name); +var isReleasable = StringComparer.OrdinalIgnoreCase.Equals(ReleasePlatform, platform) + && StringComparer.OrdinalIgnoreCase.Equals(ReleaseConfiguration, configuration); +var isMyGetRelease = !isTagged && isReleasable; +var isNuGetRelease = isTagged && isReleasable; + +Task("Clean") +.Does(()=>{ + CleanDirectories(buildDirs); +}); + +Task("Restore-NetCore") + .IsDependentOn("Clean") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + DotNetCoreRestore(project.Path); + } +}); + +Task("Build-NetCore") + .IsDependentOn("Restore-NetCore") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + Information("Building: {0}", project.Name); + DotNetCoreBuild(project.Path, new DotNetCoreBuildSettings { + Configuration = configuration + }); + } +}); + +Task("Publish-NetCore") + .IsDependentOn("Restore-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Information("Publishing: {0}, runtime: {1}", project.Name, runtime); + DotNetCorePublish(project.Path, new DotNetCorePublishSettings { + Framework = project.Framework, + Configuration = configuration, + Runtime = runtime, + OutputDirectory = outputDir.FullPath + }); + + if (IsRunningOnWindows() && (runtime == "win7-x86" || runtime == "win7-x64")) + { + Information("Patching executable subsystem for: {0}, runtime: {1}", project.Name, runtime); + var targetExe = outputDir.CombineWithFilePath(project.Name + ".exe"); + var exitCodeWithArgument = StartProcess(editbin, new ProcessSettings { + Arguments = "/subsystem:windows " + targetExe.FullPath + }); + Information("The editbin command exit code: {0}", exitCodeWithArgument); + } + } + } +}); + +Task("Zip-NetCore") + .IsDependentOn("Publish-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Zip(outputDir.FullPath, zipRootDir.CombineWithFilePath(project.Name + "-" + runtime + fileZipSuffix), + GetFiles(outputDir.FullPath + "/*.*")); + } + } +}); + +Task("Default") + .IsDependentOn("Restore-NetCore") + .IsDependentOn("Build-NetCore") + .IsDependentOn("Publish-NetCore") + .IsDependentOn("Zip-NetCore"); + +RunTarget(target);
142
add buildscript (for dans fork to test build)
0
.cake
cake
mit
AvaloniaUI/AvaloniaEdit
10068112
<NME> build.cake <BEF> ADDFILE <MSG> add buildscript (for dans fork to test build) <DFF> @@ -0,0 +1,142 @@ + +var target = Argument("target", "Default"); +var platform = Argument("platform", "AnyCPU"); +var configuration = Argument("configuration", "Release"); + +var version = "dev-0.20"; + +var editbin = @"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\bin\HostX86\x86\editbin.exe"; + +var artifactsDir = (DirectoryPath)Directory("./artifacts"); +var zipRootDir = artifactsDir.Combine("zip"); + +var fileZipSuffix = ".zip"; + +var buildDirs = GetDirectories("./src/AvalonStudio/**/bin/**") + + GetDirectories("./src/AvalonStudio/**/obj/**") + + GetDirectories("./artifacts/**/zip/**"); + +var netCoreAppsRoot= "./src/"; +var netCoreApps = new string[] { "AvaloniaEdit.Demo.NetCore" }; +var netCoreProjects = netCoreApps.Select(name => + new { + Path = string.Format("{0}/{1}", netCoreAppsRoot, name), + Name = name, + Framework = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='TargetFramework']/text()"), + Runtimes = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='RuntimeIdentifiers']/text()").Split(';') + }).ToList(); + +if (BuildSystem.AppVeyor.IsRunningOnAppVeyor) +{ + if (BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name)) + version = BuildSystem.AppVeyor.Environment.Repository.Tag.Name; + else + version += "-build" + EnvironmentVariable("APPVEYOR_BUILD_NUMBER"); +} + +var MainRepo = "danwalmsley/AvaloniaEdit"; +var MasterBranch = "master"; +var ReleasePlatform = "Any CPU"; +var ReleaseConfiguration = "Release"; + +var isPlatformAnyCPU = StringComparer.OrdinalIgnoreCase.Equals(platform, "Any CPU"); +var isPlatformX86 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x86"); +var isPlatformX64 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x64"); +var isLocalBuild = BuildSystem.IsLocalBuild; +var isRunningOnUnix = IsRunningOnUnix(); +var isRunningOnWindows = IsRunningOnWindows(); +var isRunningOnAppVeyor = BuildSystem.AppVeyor.IsRunningOnAppVeyor; +var isPullRequest = BuildSystem.AppVeyor.Environment.PullRequest.IsPullRequest; +var isMainRepo = StringComparer.OrdinalIgnoreCase.Equals(MainRepo, BuildSystem.AppVeyor.Environment.Repository.Name); +var isMasterBranch = StringComparer.OrdinalIgnoreCase.Equals(MasterBranch, BuildSystem.AppVeyor.Environment.Repository.Branch); +var isTagged = BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag + && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name); +var isReleasable = StringComparer.OrdinalIgnoreCase.Equals(ReleasePlatform, platform) + && StringComparer.OrdinalIgnoreCase.Equals(ReleaseConfiguration, configuration); +var isMyGetRelease = !isTagged && isReleasable; +var isNuGetRelease = isTagged && isReleasable; + +Task("Clean") +.Does(()=>{ + CleanDirectories(buildDirs); +}); + +Task("Restore-NetCore") + .IsDependentOn("Clean") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + DotNetCoreRestore(project.Path); + } +}); + +Task("Build-NetCore") + .IsDependentOn("Restore-NetCore") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + Information("Building: {0}", project.Name); + DotNetCoreBuild(project.Path, new DotNetCoreBuildSettings { + Configuration = configuration + }); + } +}); + +Task("Publish-NetCore") + .IsDependentOn("Restore-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Information("Publishing: {0}, runtime: {1}", project.Name, runtime); + DotNetCorePublish(project.Path, new DotNetCorePublishSettings { + Framework = project.Framework, + Configuration = configuration, + Runtime = runtime, + OutputDirectory = outputDir.FullPath + }); + + if (IsRunningOnWindows() && (runtime == "win7-x86" || runtime == "win7-x64")) + { + Information("Patching executable subsystem for: {0}, runtime: {1}", project.Name, runtime); + var targetExe = outputDir.CombineWithFilePath(project.Name + ".exe"); + var exitCodeWithArgument = StartProcess(editbin, new ProcessSettings { + Arguments = "/subsystem:windows " + targetExe.FullPath + }); + Information("The editbin command exit code: {0}", exitCodeWithArgument); + } + } + } +}); + +Task("Zip-NetCore") + .IsDependentOn("Publish-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Zip(outputDir.FullPath, zipRootDir.CombineWithFilePath(project.Name + "-" + runtime + fileZipSuffix), + GetFiles(outputDir.FullPath + "/*.*")); + } + } +}); + +Task("Default") + .IsDependentOn("Restore-NetCore") + .IsDependentOn("Build-NetCore") + .IsDependentOn("Publish-NetCore") + .IsDependentOn("Zip-NetCore"); + +RunTarget(target);
142
add buildscript (for dans fork to test build)
0
.cake
cake
mit
AvaloniaUI/AvaloniaEdit
10068113
<NME> build.cake <BEF> ADDFILE <MSG> add buildscript (for dans fork to test build) <DFF> @@ -0,0 +1,142 @@ + +var target = Argument("target", "Default"); +var platform = Argument("platform", "AnyCPU"); +var configuration = Argument("configuration", "Release"); + +var version = "dev-0.20"; + +var editbin = @"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\bin\HostX86\x86\editbin.exe"; + +var artifactsDir = (DirectoryPath)Directory("./artifacts"); +var zipRootDir = artifactsDir.Combine("zip"); + +var fileZipSuffix = ".zip"; + +var buildDirs = GetDirectories("./src/AvalonStudio/**/bin/**") + + GetDirectories("./src/AvalonStudio/**/obj/**") + + GetDirectories("./artifacts/**/zip/**"); + +var netCoreAppsRoot= "./src/"; +var netCoreApps = new string[] { "AvaloniaEdit.Demo.NetCore" }; +var netCoreProjects = netCoreApps.Select(name => + new { + Path = string.Format("{0}/{1}", netCoreAppsRoot, name), + Name = name, + Framework = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='TargetFramework']/text()"), + Runtimes = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='RuntimeIdentifiers']/text()").Split(';') + }).ToList(); + +if (BuildSystem.AppVeyor.IsRunningOnAppVeyor) +{ + if (BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name)) + version = BuildSystem.AppVeyor.Environment.Repository.Tag.Name; + else + version += "-build" + EnvironmentVariable("APPVEYOR_BUILD_NUMBER"); +} + +var MainRepo = "danwalmsley/AvaloniaEdit"; +var MasterBranch = "master"; +var ReleasePlatform = "Any CPU"; +var ReleaseConfiguration = "Release"; + +var isPlatformAnyCPU = StringComparer.OrdinalIgnoreCase.Equals(platform, "Any CPU"); +var isPlatformX86 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x86"); +var isPlatformX64 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x64"); +var isLocalBuild = BuildSystem.IsLocalBuild; +var isRunningOnUnix = IsRunningOnUnix(); +var isRunningOnWindows = IsRunningOnWindows(); +var isRunningOnAppVeyor = BuildSystem.AppVeyor.IsRunningOnAppVeyor; +var isPullRequest = BuildSystem.AppVeyor.Environment.PullRequest.IsPullRequest; +var isMainRepo = StringComparer.OrdinalIgnoreCase.Equals(MainRepo, BuildSystem.AppVeyor.Environment.Repository.Name); +var isMasterBranch = StringComparer.OrdinalIgnoreCase.Equals(MasterBranch, BuildSystem.AppVeyor.Environment.Repository.Branch); +var isTagged = BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag + && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name); +var isReleasable = StringComparer.OrdinalIgnoreCase.Equals(ReleasePlatform, platform) + && StringComparer.OrdinalIgnoreCase.Equals(ReleaseConfiguration, configuration); +var isMyGetRelease = !isTagged && isReleasable; +var isNuGetRelease = isTagged && isReleasable; + +Task("Clean") +.Does(()=>{ + CleanDirectories(buildDirs); +}); + +Task("Restore-NetCore") + .IsDependentOn("Clean") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + DotNetCoreRestore(project.Path); + } +}); + +Task("Build-NetCore") + .IsDependentOn("Restore-NetCore") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + Information("Building: {0}", project.Name); + DotNetCoreBuild(project.Path, new DotNetCoreBuildSettings { + Configuration = configuration + }); + } +}); + +Task("Publish-NetCore") + .IsDependentOn("Restore-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Information("Publishing: {0}, runtime: {1}", project.Name, runtime); + DotNetCorePublish(project.Path, new DotNetCorePublishSettings { + Framework = project.Framework, + Configuration = configuration, + Runtime = runtime, + OutputDirectory = outputDir.FullPath + }); + + if (IsRunningOnWindows() && (runtime == "win7-x86" || runtime == "win7-x64")) + { + Information("Patching executable subsystem for: {0}, runtime: {1}", project.Name, runtime); + var targetExe = outputDir.CombineWithFilePath(project.Name + ".exe"); + var exitCodeWithArgument = StartProcess(editbin, new ProcessSettings { + Arguments = "/subsystem:windows " + targetExe.FullPath + }); + Information("The editbin command exit code: {0}", exitCodeWithArgument); + } + } + } +}); + +Task("Zip-NetCore") + .IsDependentOn("Publish-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Zip(outputDir.FullPath, zipRootDir.CombineWithFilePath(project.Name + "-" + runtime + fileZipSuffix), + GetFiles(outputDir.FullPath + "/*.*")); + } + } +}); + +Task("Default") + .IsDependentOn("Restore-NetCore") + .IsDependentOn("Build-NetCore") + .IsDependentOn("Publish-NetCore") + .IsDependentOn("Zip-NetCore"); + +RunTarget(target);
142
add buildscript (for dans fork to test build)
0
.cake
cake
mit
AvaloniaUI/AvaloniaEdit
10068114
<NME> build.cake <BEF> ADDFILE <MSG> add buildscript (for dans fork to test build) <DFF> @@ -0,0 +1,142 @@ + +var target = Argument("target", "Default"); +var platform = Argument("platform", "AnyCPU"); +var configuration = Argument("configuration", "Release"); + +var version = "dev-0.20"; + +var editbin = @"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\bin\HostX86\x86\editbin.exe"; + +var artifactsDir = (DirectoryPath)Directory("./artifacts"); +var zipRootDir = artifactsDir.Combine("zip"); + +var fileZipSuffix = ".zip"; + +var buildDirs = GetDirectories("./src/AvalonStudio/**/bin/**") + + GetDirectories("./src/AvalonStudio/**/obj/**") + + GetDirectories("./artifacts/**/zip/**"); + +var netCoreAppsRoot= "./src/"; +var netCoreApps = new string[] { "AvaloniaEdit.Demo.NetCore" }; +var netCoreProjects = netCoreApps.Select(name => + new { + Path = string.Format("{0}/{1}", netCoreAppsRoot, name), + Name = name, + Framework = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='TargetFramework']/text()"), + Runtimes = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='RuntimeIdentifiers']/text()").Split(';') + }).ToList(); + +if (BuildSystem.AppVeyor.IsRunningOnAppVeyor) +{ + if (BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name)) + version = BuildSystem.AppVeyor.Environment.Repository.Tag.Name; + else + version += "-build" + EnvironmentVariable("APPVEYOR_BUILD_NUMBER"); +} + +var MainRepo = "danwalmsley/AvaloniaEdit"; +var MasterBranch = "master"; +var ReleasePlatform = "Any CPU"; +var ReleaseConfiguration = "Release"; + +var isPlatformAnyCPU = StringComparer.OrdinalIgnoreCase.Equals(platform, "Any CPU"); +var isPlatformX86 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x86"); +var isPlatformX64 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x64"); +var isLocalBuild = BuildSystem.IsLocalBuild; +var isRunningOnUnix = IsRunningOnUnix(); +var isRunningOnWindows = IsRunningOnWindows(); +var isRunningOnAppVeyor = BuildSystem.AppVeyor.IsRunningOnAppVeyor; +var isPullRequest = BuildSystem.AppVeyor.Environment.PullRequest.IsPullRequest; +var isMainRepo = StringComparer.OrdinalIgnoreCase.Equals(MainRepo, BuildSystem.AppVeyor.Environment.Repository.Name); +var isMasterBranch = StringComparer.OrdinalIgnoreCase.Equals(MasterBranch, BuildSystem.AppVeyor.Environment.Repository.Branch); +var isTagged = BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag + && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name); +var isReleasable = StringComparer.OrdinalIgnoreCase.Equals(ReleasePlatform, platform) + && StringComparer.OrdinalIgnoreCase.Equals(ReleaseConfiguration, configuration); +var isMyGetRelease = !isTagged && isReleasable; +var isNuGetRelease = isTagged && isReleasable; + +Task("Clean") +.Does(()=>{ + CleanDirectories(buildDirs); +}); + +Task("Restore-NetCore") + .IsDependentOn("Clean") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + DotNetCoreRestore(project.Path); + } +}); + +Task("Build-NetCore") + .IsDependentOn("Restore-NetCore") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + Information("Building: {0}", project.Name); + DotNetCoreBuild(project.Path, new DotNetCoreBuildSettings { + Configuration = configuration + }); + } +}); + +Task("Publish-NetCore") + .IsDependentOn("Restore-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Information("Publishing: {0}, runtime: {1}", project.Name, runtime); + DotNetCorePublish(project.Path, new DotNetCorePublishSettings { + Framework = project.Framework, + Configuration = configuration, + Runtime = runtime, + OutputDirectory = outputDir.FullPath + }); + + if (IsRunningOnWindows() && (runtime == "win7-x86" || runtime == "win7-x64")) + { + Information("Patching executable subsystem for: {0}, runtime: {1}", project.Name, runtime); + var targetExe = outputDir.CombineWithFilePath(project.Name + ".exe"); + var exitCodeWithArgument = StartProcess(editbin, new ProcessSettings { + Arguments = "/subsystem:windows " + targetExe.FullPath + }); + Information("The editbin command exit code: {0}", exitCodeWithArgument); + } + } + } +}); + +Task("Zip-NetCore") + .IsDependentOn("Publish-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Zip(outputDir.FullPath, zipRootDir.CombineWithFilePath(project.Name + "-" + runtime + fileZipSuffix), + GetFiles(outputDir.FullPath + "/*.*")); + } + } +}); + +Task("Default") + .IsDependentOn("Restore-NetCore") + .IsDependentOn("Build-NetCore") + .IsDependentOn("Publish-NetCore") + .IsDependentOn("Zip-NetCore"); + +RunTarget(target);
142
add buildscript (for dans fork to test build)
0
.cake
cake
mit
AvaloniaUI/AvaloniaEdit
10068115
<NME> build.cake <BEF> ADDFILE <MSG> add buildscript (for dans fork to test build) <DFF> @@ -0,0 +1,142 @@ + +var target = Argument("target", "Default"); +var platform = Argument("platform", "AnyCPU"); +var configuration = Argument("configuration", "Release"); + +var version = "dev-0.20"; + +var editbin = @"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\bin\HostX86\x86\editbin.exe"; + +var artifactsDir = (DirectoryPath)Directory("./artifacts"); +var zipRootDir = artifactsDir.Combine("zip"); + +var fileZipSuffix = ".zip"; + +var buildDirs = GetDirectories("./src/AvalonStudio/**/bin/**") + + GetDirectories("./src/AvalonStudio/**/obj/**") + + GetDirectories("./artifacts/**/zip/**"); + +var netCoreAppsRoot= "./src/"; +var netCoreApps = new string[] { "AvaloniaEdit.Demo.NetCore" }; +var netCoreProjects = netCoreApps.Select(name => + new { + Path = string.Format("{0}/{1}", netCoreAppsRoot, name), + Name = name, + Framework = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='TargetFramework']/text()"), + Runtimes = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='RuntimeIdentifiers']/text()").Split(';') + }).ToList(); + +if (BuildSystem.AppVeyor.IsRunningOnAppVeyor) +{ + if (BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name)) + version = BuildSystem.AppVeyor.Environment.Repository.Tag.Name; + else + version += "-build" + EnvironmentVariable("APPVEYOR_BUILD_NUMBER"); +} + +var MainRepo = "danwalmsley/AvaloniaEdit"; +var MasterBranch = "master"; +var ReleasePlatform = "Any CPU"; +var ReleaseConfiguration = "Release"; + +var isPlatformAnyCPU = StringComparer.OrdinalIgnoreCase.Equals(platform, "Any CPU"); +var isPlatformX86 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x86"); +var isPlatformX64 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x64"); +var isLocalBuild = BuildSystem.IsLocalBuild; +var isRunningOnUnix = IsRunningOnUnix(); +var isRunningOnWindows = IsRunningOnWindows(); +var isRunningOnAppVeyor = BuildSystem.AppVeyor.IsRunningOnAppVeyor; +var isPullRequest = BuildSystem.AppVeyor.Environment.PullRequest.IsPullRequest; +var isMainRepo = StringComparer.OrdinalIgnoreCase.Equals(MainRepo, BuildSystem.AppVeyor.Environment.Repository.Name); +var isMasterBranch = StringComparer.OrdinalIgnoreCase.Equals(MasterBranch, BuildSystem.AppVeyor.Environment.Repository.Branch); +var isTagged = BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag + && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name); +var isReleasable = StringComparer.OrdinalIgnoreCase.Equals(ReleasePlatform, platform) + && StringComparer.OrdinalIgnoreCase.Equals(ReleaseConfiguration, configuration); +var isMyGetRelease = !isTagged && isReleasable; +var isNuGetRelease = isTagged && isReleasable; + +Task("Clean") +.Does(()=>{ + CleanDirectories(buildDirs); +}); + +Task("Restore-NetCore") + .IsDependentOn("Clean") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + DotNetCoreRestore(project.Path); + } +}); + +Task("Build-NetCore") + .IsDependentOn("Restore-NetCore") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + Information("Building: {0}", project.Name); + DotNetCoreBuild(project.Path, new DotNetCoreBuildSettings { + Configuration = configuration + }); + } +}); + +Task("Publish-NetCore") + .IsDependentOn("Restore-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Information("Publishing: {0}, runtime: {1}", project.Name, runtime); + DotNetCorePublish(project.Path, new DotNetCorePublishSettings { + Framework = project.Framework, + Configuration = configuration, + Runtime = runtime, + OutputDirectory = outputDir.FullPath + }); + + if (IsRunningOnWindows() && (runtime == "win7-x86" || runtime == "win7-x64")) + { + Information("Patching executable subsystem for: {0}, runtime: {1}", project.Name, runtime); + var targetExe = outputDir.CombineWithFilePath(project.Name + ".exe"); + var exitCodeWithArgument = StartProcess(editbin, new ProcessSettings { + Arguments = "/subsystem:windows " + targetExe.FullPath + }); + Information("The editbin command exit code: {0}", exitCodeWithArgument); + } + } + } +}); + +Task("Zip-NetCore") + .IsDependentOn("Publish-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Zip(outputDir.FullPath, zipRootDir.CombineWithFilePath(project.Name + "-" + runtime + fileZipSuffix), + GetFiles(outputDir.FullPath + "/*.*")); + } + } +}); + +Task("Default") + .IsDependentOn("Restore-NetCore") + .IsDependentOn("Build-NetCore") + .IsDependentOn("Publish-NetCore") + .IsDependentOn("Zip-NetCore"); + +RunTarget(target);
142
add buildscript (for dans fork to test build)
0
.cake
cake
mit
AvaloniaUI/AvaloniaEdit
10068116
<NME> build.cake <BEF> ADDFILE <MSG> add buildscript (for dans fork to test build) <DFF> @@ -0,0 +1,142 @@ + +var target = Argument("target", "Default"); +var platform = Argument("platform", "AnyCPU"); +var configuration = Argument("configuration", "Release"); + +var version = "dev-0.20"; + +var editbin = @"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\bin\HostX86\x86\editbin.exe"; + +var artifactsDir = (DirectoryPath)Directory("./artifacts"); +var zipRootDir = artifactsDir.Combine("zip"); + +var fileZipSuffix = ".zip"; + +var buildDirs = GetDirectories("./src/AvalonStudio/**/bin/**") + + GetDirectories("./src/AvalonStudio/**/obj/**") + + GetDirectories("./artifacts/**/zip/**"); + +var netCoreAppsRoot= "./src/"; +var netCoreApps = new string[] { "AvaloniaEdit.Demo.NetCore" }; +var netCoreProjects = netCoreApps.Select(name => + new { + Path = string.Format("{0}/{1}", netCoreAppsRoot, name), + Name = name, + Framework = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='TargetFramework']/text()"), + Runtimes = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='RuntimeIdentifiers']/text()").Split(';') + }).ToList(); + +if (BuildSystem.AppVeyor.IsRunningOnAppVeyor) +{ + if (BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name)) + version = BuildSystem.AppVeyor.Environment.Repository.Tag.Name; + else + version += "-build" + EnvironmentVariable("APPVEYOR_BUILD_NUMBER"); +} + +var MainRepo = "danwalmsley/AvaloniaEdit"; +var MasterBranch = "master"; +var ReleasePlatform = "Any CPU"; +var ReleaseConfiguration = "Release"; + +var isPlatformAnyCPU = StringComparer.OrdinalIgnoreCase.Equals(platform, "Any CPU"); +var isPlatformX86 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x86"); +var isPlatformX64 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x64"); +var isLocalBuild = BuildSystem.IsLocalBuild; +var isRunningOnUnix = IsRunningOnUnix(); +var isRunningOnWindows = IsRunningOnWindows(); +var isRunningOnAppVeyor = BuildSystem.AppVeyor.IsRunningOnAppVeyor; +var isPullRequest = BuildSystem.AppVeyor.Environment.PullRequest.IsPullRequest; +var isMainRepo = StringComparer.OrdinalIgnoreCase.Equals(MainRepo, BuildSystem.AppVeyor.Environment.Repository.Name); +var isMasterBranch = StringComparer.OrdinalIgnoreCase.Equals(MasterBranch, BuildSystem.AppVeyor.Environment.Repository.Branch); +var isTagged = BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag + && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name); +var isReleasable = StringComparer.OrdinalIgnoreCase.Equals(ReleasePlatform, platform) + && StringComparer.OrdinalIgnoreCase.Equals(ReleaseConfiguration, configuration); +var isMyGetRelease = !isTagged && isReleasable; +var isNuGetRelease = isTagged && isReleasable; + +Task("Clean") +.Does(()=>{ + CleanDirectories(buildDirs); +}); + +Task("Restore-NetCore") + .IsDependentOn("Clean") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + DotNetCoreRestore(project.Path); + } +}); + +Task("Build-NetCore") + .IsDependentOn("Restore-NetCore") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + Information("Building: {0}", project.Name); + DotNetCoreBuild(project.Path, new DotNetCoreBuildSettings { + Configuration = configuration + }); + } +}); + +Task("Publish-NetCore") + .IsDependentOn("Restore-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Information("Publishing: {0}, runtime: {1}", project.Name, runtime); + DotNetCorePublish(project.Path, new DotNetCorePublishSettings { + Framework = project.Framework, + Configuration = configuration, + Runtime = runtime, + OutputDirectory = outputDir.FullPath + }); + + if (IsRunningOnWindows() && (runtime == "win7-x86" || runtime == "win7-x64")) + { + Information("Patching executable subsystem for: {0}, runtime: {1}", project.Name, runtime); + var targetExe = outputDir.CombineWithFilePath(project.Name + ".exe"); + var exitCodeWithArgument = StartProcess(editbin, new ProcessSettings { + Arguments = "/subsystem:windows " + targetExe.FullPath + }); + Information("The editbin command exit code: {0}", exitCodeWithArgument); + } + } + } +}); + +Task("Zip-NetCore") + .IsDependentOn("Publish-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Zip(outputDir.FullPath, zipRootDir.CombineWithFilePath(project.Name + "-" + runtime + fileZipSuffix), + GetFiles(outputDir.FullPath + "/*.*")); + } + } +}); + +Task("Default") + .IsDependentOn("Restore-NetCore") + .IsDependentOn("Build-NetCore") + .IsDependentOn("Publish-NetCore") + .IsDependentOn("Zip-NetCore"); + +RunTarget(target);
142
add buildscript (for dans fork to test build)
0
.cake
cake
mit
AvaloniaUI/AvaloniaEdit
10068117
<NME> build.cake <BEF> ADDFILE <MSG> add buildscript (for dans fork to test build) <DFF> @@ -0,0 +1,142 @@ + +var target = Argument("target", "Default"); +var platform = Argument("platform", "AnyCPU"); +var configuration = Argument("configuration", "Release"); + +var version = "dev-0.20"; + +var editbin = @"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\bin\HostX86\x86\editbin.exe"; + +var artifactsDir = (DirectoryPath)Directory("./artifacts"); +var zipRootDir = artifactsDir.Combine("zip"); + +var fileZipSuffix = ".zip"; + +var buildDirs = GetDirectories("./src/AvalonStudio/**/bin/**") + + GetDirectories("./src/AvalonStudio/**/obj/**") + + GetDirectories("./artifacts/**/zip/**"); + +var netCoreAppsRoot= "./src/"; +var netCoreApps = new string[] { "AvaloniaEdit.Demo.NetCore" }; +var netCoreProjects = netCoreApps.Select(name => + new { + Path = string.Format("{0}/{1}", netCoreAppsRoot, name), + Name = name, + Framework = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='TargetFramework']/text()"), + Runtimes = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='RuntimeIdentifiers']/text()").Split(';') + }).ToList(); + +if (BuildSystem.AppVeyor.IsRunningOnAppVeyor) +{ + if (BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name)) + version = BuildSystem.AppVeyor.Environment.Repository.Tag.Name; + else + version += "-build" + EnvironmentVariable("APPVEYOR_BUILD_NUMBER"); +} + +var MainRepo = "danwalmsley/AvaloniaEdit"; +var MasterBranch = "master"; +var ReleasePlatform = "Any CPU"; +var ReleaseConfiguration = "Release"; + +var isPlatformAnyCPU = StringComparer.OrdinalIgnoreCase.Equals(platform, "Any CPU"); +var isPlatformX86 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x86"); +var isPlatformX64 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x64"); +var isLocalBuild = BuildSystem.IsLocalBuild; +var isRunningOnUnix = IsRunningOnUnix(); +var isRunningOnWindows = IsRunningOnWindows(); +var isRunningOnAppVeyor = BuildSystem.AppVeyor.IsRunningOnAppVeyor; +var isPullRequest = BuildSystem.AppVeyor.Environment.PullRequest.IsPullRequest; +var isMainRepo = StringComparer.OrdinalIgnoreCase.Equals(MainRepo, BuildSystem.AppVeyor.Environment.Repository.Name); +var isMasterBranch = StringComparer.OrdinalIgnoreCase.Equals(MasterBranch, BuildSystem.AppVeyor.Environment.Repository.Branch); +var isTagged = BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag + && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name); +var isReleasable = StringComparer.OrdinalIgnoreCase.Equals(ReleasePlatform, platform) + && StringComparer.OrdinalIgnoreCase.Equals(ReleaseConfiguration, configuration); +var isMyGetRelease = !isTagged && isReleasable; +var isNuGetRelease = isTagged && isReleasable; + +Task("Clean") +.Does(()=>{ + CleanDirectories(buildDirs); +}); + +Task("Restore-NetCore") + .IsDependentOn("Clean") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + DotNetCoreRestore(project.Path); + } +}); + +Task("Build-NetCore") + .IsDependentOn("Restore-NetCore") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + Information("Building: {0}", project.Name); + DotNetCoreBuild(project.Path, new DotNetCoreBuildSettings { + Configuration = configuration + }); + } +}); + +Task("Publish-NetCore") + .IsDependentOn("Restore-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Information("Publishing: {0}, runtime: {1}", project.Name, runtime); + DotNetCorePublish(project.Path, new DotNetCorePublishSettings { + Framework = project.Framework, + Configuration = configuration, + Runtime = runtime, + OutputDirectory = outputDir.FullPath + }); + + if (IsRunningOnWindows() && (runtime == "win7-x86" || runtime == "win7-x64")) + { + Information("Patching executable subsystem for: {0}, runtime: {1}", project.Name, runtime); + var targetExe = outputDir.CombineWithFilePath(project.Name + ".exe"); + var exitCodeWithArgument = StartProcess(editbin, new ProcessSettings { + Arguments = "/subsystem:windows " + targetExe.FullPath + }); + Information("The editbin command exit code: {0}", exitCodeWithArgument); + } + } + } +}); + +Task("Zip-NetCore") + .IsDependentOn("Publish-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Zip(outputDir.FullPath, zipRootDir.CombineWithFilePath(project.Name + "-" + runtime + fileZipSuffix), + GetFiles(outputDir.FullPath + "/*.*")); + } + } +}); + +Task("Default") + .IsDependentOn("Restore-NetCore") + .IsDependentOn("Build-NetCore") + .IsDependentOn("Publish-NetCore") + .IsDependentOn("Zip-NetCore"); + +RunTarget(target);
142
add buildscript (for dans fork to test build)
0
.cake
cake
mit
AvaloniaUI/AvaloniaEdit
10068118
<NME> build.cake <BEF> ADDFILE <MSG> add buildscript (for dans fork to test build) <DFF> @@ -0,0 +1,142 @@ + +var target = Argument("target", "Default"); +var platform = Argument("platform", "AnyCPU"); +var configuration = Argument("configuration", "Release"); + +var version = "dev-0.20"; + +var editbin = @"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\bin\HostX86\x86\editbin.exe"; + +var artifactsDir = (DirectoryPath)Directory("./artifacts"); +var zipRootDir = artifactsDir.Combine("zip"); + +var fileZipSuffix = ".zip"; + +var buildDirs = GetDirectories("./src/AvalonStudio/**/bin/**") + + GetDirectories("./src/AvalonStudio/**/obj/**") + + GetDirectories("./artifacts/**/zip/**"); + +var netCoreAppsRoot= "./src/"; +var netCoreApps = new string[] { "AvaloniaEdit.Demo.NetCore" }; +var netCoreProjects = netCoreApps.Select(name => + new { + Path = string.Format("{0}/{1}", netCoreAppsRoot, name), + Name = name, + Framework = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='TargetFramework']/text()"), + Runtimes = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='RuntimeIdentifiers']/text()").Split(';') + }).ToList(); + +if (BuildSystem.AppVeyor.IsRunningOnAppVeyor) +{ + if (BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name)) + version = BuildSystem.AppVeyor.Environment.Repository.Tag.Name; + else + version += "-build" + EnvironmentVariable("APPVEYOR_BUILD_NUMBER"); +} + +var MainRepo = "danwalmsley/AvaloniaEdit"; +var MasterBranch = "master"; +var ReleasePlatform = "Any CPU"; +var ReleaseConfiguration = "Release"; + +var isPlatformAnyCPU = StringComparer.OrdinalIgnoreCase.Equals(platform, "Any CPU"); +var isPlatformX86 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x86"); +var isPlatformX64 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x64"); +var isLocalBuild = BuildSystem.IsLocalBuild; +var isRunningOnUnix = IsRunningOnUnix(); +var isRunningOnWindows = IsRunningOnWindows(); +var isRunningOnAppVeyor = BuildSystem.AppVeyor.IsRunningOnAppVeyor; +var isPullRequest = BuildSystem.AppVeyor.Environment.PullRequest.IsPullRequest; +var isMainRepo = StringComparer.OrdinalIgnoreCase.Equals(MainRepo, BuildSystem.AppVeyor.Environment.Repository.Name); +var isMasterBranch = StringComparer.OrdinalIgnoreCase.Equals(MasterBranch, BuildSystem.AppVeyor.Environment.Repository.Branch); +var isTagged = BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag + && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name); +var isReleasable = StringComparer.OrdinalIgnoreCase.Equals(ReleasePlatform, platform) + && StringComparer.OrdinalIgnoreCase.Equals(ReleaseConfiguration, configuration); +var isMyGetRelease = !isTagged && isReleasable; +var isNuGetRelease = isTagged && isReleasable; + +Task("Clean") +.Does(()=>{ + CleanDirectories(buildDirs); +}); + +Task("Restore-NetCore") + .IsDependentOn("Clean") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + DotNetCoreRestore(project.Path); + } +}); + +Task("Build-NetCore") + .IsDependentOn("Restore-NetCore") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + Information("Building: {0}", project.Name); + DotNetCoreBuild(project.Path, new DotNetCoreBuildSettings { + Configuration = configuration + }); + } +}); + +Task("Publish-NetCore") + .IsDependentOn("Restore-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Information("Publishing: {0}, runtime: {1}", project.Name, runtime); + DotNetCorePublish(project.Path, new DotNetCorePublishSettings { + Framework = project.Framework, + Configuration = configuration, + Runtime = runtime, + OutputDirectory = outputDir.FullPath + }); + + if (IsRunningOnWindows() && (runtime == "win7-x86" || runtime == "win7-x64")) + { + Information("Patching executable subsystem for: {0}, runtime: {1}", project.Name, runtime); + var targetExe = outputDir.CombineWithFilePath(project.Name + ".exe"); + var exitCodeWithArgument = StartProcess(editbin, new ProcessSettings { + Arguments = "/subsystem:windows " + targetExe.FullPath + }); + Information("The editbin command exit code: {0}", exitCodeWithArgument); + } + } + } +}); + +Task("Zip-NetCore") + .IsDependentOn("Publish-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Zip(outputDir.FullPath, zipRootDir.CombineWithFilePath(project.Name + "-" + runtime + fileZipSuffix), + GetFiles(outputDir.FullPath + "/*.*")); + } + } +}); + +Task("Default") + .IsDependentOn("Restore-NetCore") + .IsDependentOn("Build-NetCore") + .IsDependentOn("Publish-NetCore") + .IsDependentOn("Zip-NetCore"); + +RunTarget(target);
142
add buildscript (for dans fork to test build)
0
.cake
cake
mit
AvaloniaUI/AvaloniaEdit
10068119
<NME> build.cake <BEF> ADDFILE <MSG> add buildscript (for dans fork to test build) <DFF> @@ -0,0 +1,142 @@ + +var target = Argument("target", "Default"); +var platform = Argument("platform", "AnyCPU"); +var configuration = Argument("configuration", "Release"); + +var version = "dev-0.20"; + +var editbin = @"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\bin\HostX86\x86\editbin.exe"; + +var artifactsDir = (DirectoryPath)Directory("./artifacts"); +var zipRootDir = artifactsDir.Combine("zip"); + +var fileZipSuffix = ".zip"; + +var buildDirs = GetDirectories("./src/AvalonStudio/**/bin/**") + + GetDirectories("./src/AvalonStudio/**/obj/**") + + GetDirectories("./artifacts/**/zip/**"); + +var netCoreAppsRoot= "./src/"; +var netCoreApps = new string[] { "AvaloniaEdit.Demo.NetCore" }; +var netCoreProjects = netCoreApps.Select(name => + new { + Path = string.Format("{0}/{1}", netCoreAppsRoot, name), + Name = name, + Framework = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='TargetFramework']/text()"), + Runtimes = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='RuntimeIdentifiers']/text()").Split(';') + }).ToList(); + +if (BuildSystem.AppVeyor.IsRunningOnAppVeyor) +{ + if (BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name)) + version = BuildSystem.AppVeyor.Environment.Repository.Tag.Name; + else + version += "-build" + EnvironmentVariable("APPVEYOR_BUILD_NUMBER"); +} + +var MainRepo = "danwalmsley/AvaloniaEdit"; +var MasterBranch = "master"; +var ReleasePlatform = "Any CPU"; +var ReleaseConfiguration = "Release"; + +var isPlatformAnyCPU = StringComparer.OrdinalIgnoreCase.Equals(platform, "Any CPU"); +var isPlatformX86 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x86"); +var isPlatformX64 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x64"); +var isLocalBuild = BuildSystem.IsLocalBuild; +var isRunningOnUnix = IsRunningOnUnix(); +var isRunningOnWindows = IsRunningOnWindows(); +var isRunningOnAppVeyor = BuildSystem.AppVeyor.IsRunningOnAppVeyor; +var isPullRequest = BuildSystem.AppVeyor.Environment.PullRequest.IsPullRequest; +var isMainRepo = StringComparer.OrdinalIgnoreCase.Equals(MainRepo, BuildSystem.AppVeyor.Environment.Repository.Name); +var isMasterBranch = StringComparer.OrdinalIgnoreCase.Equals(MasterBranch, BuildSystem.AppVeyor.Environment.Repository.Branch); +var isTagged = BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag + && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name); +var isReleasable = StringComparer.OrdinalIgnoreCase.Equals(ReleasePlatform, platform) + && StringComparer.OrdinalIgnoreCase.Equals(ReleaseConfiguration, configuration); +var isMyGetRelease = !isTagged && isReleasable; +var isNuGetRelease = isTagged && isReleasable; + +Task("Clean") +.Does(()=>{ + CleanDirectories(buildDirs); +}); + +Task("Restore-NetCore") + .IsDependentOn("Clean") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + DotNetCoreRestore(project.Path); + } +}); + +Task("Build-NetCore") + .IsDependentOn("Restore-NetCore") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + Information("Building: {0}", project.Name); + DotNetCoreBuild(project.Path, new DotNetCoreBuildSettings { + Configuration = configuration + }); + } +}); + +Task("Publish-NetCore") + .IsDependentOn("Restore-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Information("Publishing: {0}, runtime: {1}", project.Name, runtime); + DotNetCorePublish(project.Path, new DotNetCorePublishSettings { + Framework = project.Framework, + Configuration = configuration, + Runtime = runtime, + OutputDirectory = outputDir.FullPath + }); + + if (IsRunningOnWindows() && (runtime == "win7-x86" || runtime == "win7-x64")) + { + Information("Patching executable subsystem for: {0}, runtime: {1}", project.Name, runtime); + var targetExe = outputDir.CombineWithFilePath(project.Name + ".exe"); + var exitCodeWithArgument = StartProcess(editbin, new ProcessSettings { + Arguments = "/subsystem:windows " + targetExe.FullPath + }); + Information("The editbin command exit code: {0}", exitCodeWithArgument); + } + } + } +}); + +Task("Zip-NetCore") + .IsDependentOn("Publish-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Zip(outputDir.FullPath, zipRootDir.CombineWithFilePath(project.Name + "-" + runtime + fileZipSuffix), + GetFiles(outputDir.FullPath + "/*.*")); + } + } +}); + +Task("Default") + .IsDependentOn("Restore-NetCore") + .IsDependentOn("Build-NetCore") + .IsDependentOn("Publish-NetCore") + .IsDependentOn("Zip-NetCore"); + +RunTarget(target);
142
add buildscript (for dans fork to test build)
0
.cake
cake
mit
AvaloniaUI/AvaloniaEdit
10068120
<NME> build.cake <BEF> ADDFILE <MSG> add buildscript (for dans fork to test build) <DFF> @@ -0,0 +1,142 @@ + +var target = Argument("target", "Default"); +var platform = Argument("platform", "AnyCPU"); +var configuration = Argument("configuration", "Release"); + +var version = "dev-0.20"; + +var editbin = @"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\bin\HostX86\x86\editbin.exe"; + +var artifactsDir = (DirectoryPath)Directory("./artifacts"); +var zipRootDir = artifactsDir.Combine("zip"); + +var fileZipSuffix = ".zip"; + +var buildDirs = GetDirectories("./src/AvalonStudio/**/bin/**") + + GetDirectories("./src/AvalonStudio/**/obj/**") + + GetDirectories("./artifacts/**/zip/**"); + +var netCoreAppsRoot= "./src/"; +var netCoreApps = new string[] { "AvaloniaEdit.Demo.NetCore" }; +var netCoreProjects = netCoreApps.Select(name => + new { + Path = string.Format("{0}/{1}", netCoreAppsRoot, name), + Name = name, + Framework = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='TargetFramework']/text()"), + Runtimes = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='RuntimeIdentifiers']/text()").Split(';') + }).ToList(); + +if (BuildSystem.AppVeyor.IsRunningOnAppVeyor) +{ + if (BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name)) + version = BuildSystem.AppVeyor.Environment.Repository.Tag.Name; + else + version += "-build" + EnvironmentVariable("APPVEYOR_BUILD_NUMBER"); +} + +var MainRepo = "danwalmsley/AvaloniaEdit"; +var MasterBranch = "master"; +var ReleasePlatform = "Any CPU"; +var ReleaseConfiguration = "Release"; + +var isPlatformAnyCPU = StringComparer.OrdinalIgnoreCase.Equals(platform, "Any CPU"); +var isPlatformX86 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x86"); +var isPlatformX64 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x64"); +var isLocalBuild = BuildSystem.IsLocalBuild; +var isRunningOnUnix = IsRunningOnUnix(); +var isRunningOnWindows = IsRunningOnWindows(); +var isRunningOnAppVeyor = BuildSystem.AppVeyor.IsRunningOnAppVeyor; +var isPullRequest = BuildSystem.AppVeyor.Environment.PullRequest.IsPullRequest; +var isMainRepo = StringComparer.OrdinalIgnoreCase.Equals(MainRepo, BuildSystem.AppVeyor.Environment.Repository.Name); +var isMasterBranch = StringComparer.OrdinalIgnoreCase.Equals(MasterBranch, BuildSystem.AppVeyor.Environment.Repository.Branch); +var isTagged = BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag + && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name); +var isReleasable = StringComparer.OrdinalIgnoreCase.Equals(ReleasePlatform, platform) + && StringComparer.OrdinalIgnoreCase.Equals(ReleaseConfiguration, configuration); +var isMyGetRelease = !isTagged && isReleasable; +var isNuGetRelease = isTagged && isReleasable; + +Task("Clean") +.Does(()=>{ + CleanDirectories(buildDirs); +}); + +Task("Restore-NetCore") + .IsDependentOn("Clean") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + DotNetCoreRestore(project.Path); + } +}); + +Task("Build-NetCore") + .IsDependentOn("Restore-NetCore") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + Information("Building: {0}", project.Name); + DotNetCoreBuild(project.Path, new DotNetCoreBuildSettings { + Configuration = configuration + }); + } +}); + +Task("Publish-NetCore") + .IsDependentOn("Restore-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Information("Publishing: {0}, runtime: {1}", project.Name, runtime); + DotNetCorePublish(project.Path, new DotNetCorePublishSettings { + Framework = project.Framework, + Configuration = configuration, + Runtime = runtime, + OutputDirectory = outputDir.FullPath + }); + + if (IsRunningOnWindows() && (runtime == "win7-x86" || runtime == "win7-x64")) + { + Information("Patching executable subsystem for: {0}, runtime: {1}", project.Name, runtime); + var targetExe = outputDir.CombineWithFilePath(project.Name + ".exe"); + var exitCodeWithArgument = StartProcess(editbin, new ProcessSettings { + Arguments = "/subsystem:windows " + targetExe.FullPath + }); + Information("The editbin command exit code: {0}", exitCodeWithArgument); + } + } + } +}); + +Task("Zip-NetCore") + .IsDependentOn("Publish-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Zip(outputDir.FullPath, zipRootDir.CombineWithFilePath(project.Name + "-" + runtime + fileZipSuffix), + GetFiles(outputDir.FullPath + "/*.*")); + } + } +}); + +Task("Default") + .IsDependentOn("Restore-NetCore") + .IsDependentOn("Build-NetCore") + .IsDependentOn("Publish-NetCore") + .IsDependentOn("Zip-NetCore"); + +RunTarget(target);
142
add buildscript (for dans fork to test build)
0
.cake
cake
mit
AvaloniaUI/AvaloniaEdit
10068121
<NME> build.cake <BEF> ADDFILE <MSG> add buildscript (for dans fork to test build) <DFF> @@ -0,0 +1,142 @@ + +var target = Argument("target", "Default"); +var platform = Argument("platform", "AnyCPU"); +var configuration = Argument("configuration", "Release"); + +var version = "dev-0.20"; + +var editbin = @"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\bin\HostX86\x86\editbin.exe"; + +var artifactsDir = (DirectoryPath)Directory("./artifacts"); +var zipRootDir = artifactsDir.Combine("zip"); + +var fileZipSuffix = ".zip"; + +var buildDirs = GetDirectories("./src/AvalonStudio/**/bin/**") + + GetDirectories("./src/AvalonStudio/**/obj/**") + + GetDirectories("./artifacts/**/zip/**"); + +var netCoreAppsRoot= "./src/"; +var netCoreApps = new string[] { "AvaloniaEdit.Demo.NetCore" }; +var netCoreProjects = netCoreApps.Select(name => + new { + Path = string.Format("{0}/{1}", netCoreAppsRoot, name), + Name = name, + Framework = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='TargetFramework']/text()"), + Runtimes = XmlPeek(string.Format("{0}/{1}/{1}.csproj", netCoreAppsRoot, name), "//*[local-name()='RuntimeIdentifiers']/text()").Split(';') + }).ToList(); + +if (BuildSystem.AppVeyor.IsRunningOnAppVeyor) +{ + if (BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name)) + version = BuildSystem.AppVeyor.Environment.Repository.Tag.Name; + else + version += "-build" + EnvironmentVariable("APPVEYOR_BUILD_NUMBER"); +} + +var MainRepo = "danwalmsley/AvaloniaEdit"; +var MasterBranch = "master"; +var ReleasePlatform = "Any CPU"; +var ReleaseConfiguration = "Release"; + +var isPlatformAnyCPU = StringComparer.OrdinalIgnoreCase.Equals(platform, "Any CPU"); +var isPlatformX86 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x86"); +var isPlatformX64 = StringComparer.OrdinalIgnoreCase.Equals(platform, "x64"); +var isLocalBuild = BuildSystem.IsLocalBuild; +var isRunningOnUnix = IsRunningOnUnix(); +var isRunningOnWindows = IsRunningOnWindows(); +var isRunningOnAppVeyor = BuildSystem.AppVeyor.IsRunningOnAppVeyor; +var isPullRequest = BuildSystem.AppVeyor.Environment.PullRequest.IsPullRequest; +var isMainRepo = StringComparer.OrdinalIgnoreCase.Equals(MainRepo, BuildSystem.AppVeyor.Environment.Repository.Name); +var isMasterBranch = StringComparer.OrdinalIgnoreCase.Equals(MasterBranch, BuildSystem.AppVeyor.Environment.Repository.Branch); +var isTagged = BuildSystem.AppVeyor.Environment.Repository.Tag.IsTag + && !string.IsNullOrWhiteSpace(BuildSystem.AppVeyor.Environment.Repository.Tag.Name); +var isReleasable = StringComparer.OrdinalIgnoreCase.Equals(ReleasePlatform, platform) + && StringComparer.OrdinalIgnoreCase.Equals(ReleaseConfiguration, configuration); +var isMyGetRelease = !isTagged && isReleasable; +var isNuGetRelease = isTagged && isReleasable; + +Task("Clean") +.Does(()=>{ + CleanDirectories(buildDirs); +}); + +Task("Restore-NetCore") + .IsDependentOn("Clean") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + DotNetCoreRestore(project.Path); + } +}); + +Task("Build-NetCore") + .IsDependentOn("Restore-NetCore") + .Does(() => +{ + foreach (var project in netCoreProjects) + { + Information("Building: {0}", project.Name); + DotNetCoreBuild(project.Path, new DotNetCoreBuildSettings { + Configuration = configuration + }); + } +}); + +Task("Publish-NetCore") + .IsDependentOn("Restore-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Information("Publishing: {0}, runtime: {1}", project.Name, runtime); + DotNetCorePublish(project.Path, new DotNetCorePublishSettings { + Framework = project.Framework, + Configuration = configuration, + Runtime = runtime, + OutputDirectory = outputDir.FullPath + }); + + if (IsRunningOnWindows() && (runtime == "win7-x86" || runtime == "win7-x64")) + { + Information("Patching executable subsystem for: {0}, runtime: {1}", project.Name, runtime); + var targetExe = outputDir.CombineWithFilePath(project.Name + ".exe"); + var exitCodeWithArgument = StartProcess(editbin, new ProcessSettings { + Arguments = "/subsystem:windows " + targetExe.FullPath + }); + Information("The editbin command exit code: {0}", exitCodeWithArgument); + } + } + } +}); + +Task("Zip-NetCore") + .IsDependentOn("Publish-NetCore") + .WithCriteria(()=>isMainRepo && isMasterBranch) + .Does(() => +{ + foreach (var project in netCoreProjects) + { + foreach(var runtime in project.Runtimes) + { + var outputDir = zipRootDir.Combine(project.Name + "-" + runtime); + + Zip(outputDir.FullPath, zipRootDir.CombineWithFilePath(project.Name + "-" + runtime + fileZipSuffix), + GetFiles(outputDir.FullPath + "/*.*")); + } + } +}); + +Task("Default") + .IsDependentOn("Restore-NetCore") + .IsDependentOn("Build-NetCore") + .IsDependentOn("Publish-NetCore") + .IsDependentOn("Zip-NetCore"); + +RunTarget(target);
142
add buildscript (for dans fork to test build)
0
.cake
cake
mit
AvaloniaUI/AvaloniaEdit
10068122
<NME> README.md <BEF> # FruitMachine [![Build Status](https://travis-ci.org/ftlabs/fruitmachine.png?branch=master)](https://travis-ci.org/ftlabs/fruitmachine) [![Coverage Status](https://coveralls.io/repos/matthew-andrews/fruitmachine/badge.png?branch=coverage)](https://coveralls.io/r/matthew-andrews/fruitmachine?branch=coverage) A lightweight component layout engine for client and server. FruitMachine is designed to build rich interactive layouts from modular, reusable components. It's light and unopinionated so that it can be applied to almost any layout problem. FruitMachine is currently powering the [FT Web App](http://apps.ft.com/ftwebapp/). ```js // Define a module var Apple = fruitmachine.define({ name: 'apple', template: function(){ return 'hello' } }); // Create a module var apple = new Apple(); // Render it apple.render(); 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) - [Extending](docs/extending-modules.md) - [Server-side rendering](docs/server-side-rendering.md) - [API](docs/api.md) - [Events](docs/events.md) ## Tests #### With PhantomJS ``` $ npm install $ npm test ``` #### Without PhantomJS ``` $ node_modules/.bin/buster-static ``` ...then visit http://localhost:8282/ in browser ## Author - **Wilson Page** - [@wilsonpage](http://github.com/wilsonpage) ## Contributors - **Wilson Page** - [@wilsonpage](http://github.com/wilsonpage) - **Matt Andrews** - [@matthew-andrews](http://github.com/matthew-andrews) ## License Copyright (c) 2018 The Financial Times Limited Licensed under the MIT license. ## Credits and collaboration FruitMachine is largely unmaintained/finished. All open source code released by FT Labs is licenced under the MIT licence. We welcome comments, feedback and suggestions. Please feel free to raise an issue or pull request. <MSG> Update badge to FT Labs <DFF> @@ -1,4 +1,4 @@ -# FruitMachine [![Build Status](https://travis-ci.org/ftlabs/fruitmachine.png?branch=master)](https://travis-ci.org/ftlabs/fruitmachine) [![Coverage Status](https://coveralls.io/repos/matthew-andrews/fruitmachine/badge.png?branch=coverage)](https://coveralls.io/r/matthew-andrews/fruitmachine?branch=coverage) +# FruitMachine [![Build Status](https://travis-ci.org/ftlabs/fruitmachine.png?branch=master)](https://travis-ci.org/ftlabs/fruitmachine) [![Coverage Status](https://coveralls.io/repos/ftlabs/fruitmachine/badge.png?branch=coverage)](https://coveralls.io/r/ftlabs/fruitmachine?branch=coverage) A lightweight component layout engine for client and server.
1
Update badge to FT Labs
1
.md
md
mit
ftlabs/fruitmachine
10068123
<NME> README.md <BEF> # LoadJS <img src="https://www.muicss.com/static/images/loadjs.svg" width="250px"> LoadJS is a tiny async loader for modern browsers (899 bytes). [![Dependency Status](https://david-dm.org/muicss/loadjs.svg)](https://david-dm.org/muicss/loadjs) [![devDependency Status](https://david-dm.org/muicss/loadjs/dev-status.svg)](https://david-dm.org/muicss/loadjs?type=dev) ## Introduction LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript and CSS files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.js) in your &lt;html&gt; (possibly in the &lt;head&gt; tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload. LoadJS is based on the excellent [$script](https://github.com/ded/script.js) library by [Dustin Diaz](https://github.com/ded). We kept the behavior of the library the same but we re-wrote the code from scratch to add support for success/error callbacks and to optimize the library for modern browsers. LoadJS is 711 bytes (minified + gzipped). Here's an example of what you can do with LoadJS: ```html <script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script> <script> // define a dependency bundle and execute code when it loads loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); </script> ``` You can also use more advanced syntax for more options: ```html <script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script> <script> // define a dependency bundle with advanced options loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { before: function(path, scriptEl) { /* execute code before fetch */ }, async: true, // load files synchronously or asynchronously (default: true) numRetries: 3 // see caveats about using numRetries with async:false (default: 0), returnPromise: false // return Promise object (default: false) }); loadjs.ready('foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(depsNotFound) { /* foobar bundle load failed */ }, }); </script> ``` The latest version of LoadJS can be found in the `dist/` directory in this repository: * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js) (for development) * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js) (for production) It's also available from these public CDNs: * UNPKG * [https://unpkg.com/[email protected]/dist/loadjs.js](https://unpkg.com/[email protected]/dist/loadjs.js) (for development) * [https://unpkg.com/[email protected]/dist/loadjs.min.js](https://unpkg.com/[email protected]/dist/loadjs.min.js) (for production) * CDNJS * [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js) (for development) * [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js) (for production) You can also use it as a CJS or AMD module: ```bash $ npm install --save loadjs ``` ```javascript var loadjs = require('loadjs'); loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); ``` ## Browser Support * IE9+ (`async: false` support only works in IE10+) * Opera 12+ * Safari 5+ * Chrome * Firefox * iOS 6+ * Android 4.4+ LoadJS also detects script load failures from AdBlock Plus and Ghostery in: * Safari * Chrome Note: LoadJS treats empty CSS files as load failures in IE9-11 and uses `rel="preload"` to load CSS files in Edge (to get around lack of support for onerror events on `<link rel="stylesheet">` tags) ## Documentation 1. Load a single file ```javascript loadjs('/path/to/foo.js', function() { /* foo.js loaded */ }); ``` 1. Fetch files in parallel and load them asynchronously ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], function() { /* foo.js and bar.js loaded */ }); ``` 1. Fetch JavaScript, CSS and image files ```javascript loadjs(['/path/to/foo.css', '/path/to/bar.png', 'path/to/thunk.js'], function() { /* foo.css, bar.png and thunk.js loaded */ }); ``` 1. Force treat file as CSS stylesheet ```javascript loadjs(['css!/path/to/cssfile.custom'], function() { /* cssfile.custom loaded as stylesheet */ }); ``` 1. Force treat file as image ```javascript loadjs(['img!/path/to/image.custom'], function() { /* image.custom loaded */ }); ``` 1. Add a bundle id ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }); ``` 1. Use .ready() to define bundles and callbacks separately ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); ``` 1. Use multiple bundles in .ready() dependency lists ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs(['/path/to/bar1.js', '/path/to/bar2.js'], 'bar'); loadjs.ready(['foo', 'bar'], function() { /* foo.js & bar1.js & bar2.js loaded */ }); ``` 1. Chain .ready() together ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs .ready('foo', function() { /* foo.js loaded */ }) .ready('bar', function() { /* bar.js loaded */ }); ``` 1. Use Promises to register callbacks ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], {returnPromise: true}) .then(function() { /* foo.js & bar.js loaded */ }) .catch(function(pathsNotFound) { /* at least one didn't load */ }); ``` 1. Check if bundle has already been defined ```javascript if (!loadjs.isDefined('foobar')) { loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }); } ``` 1. Fetch files in parallel and load them in series ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() { /* foo.js and bar.js loaded in series */ }, async: false }); ``` 1. Add an error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ } }); ``` 1. Retry files before calling the error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ }, numRetries: 3 }); // NOTE: Using `numRetries` with `async: false` can cause files to load out-of-sync on retries ``` 1. Execute a callback before script tags are embedded ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { /* called for each script node before being embedded */ if (path === '/path/to/foo.js') scriptEl.crossOrigin = true; } }); ``` 1. Bypass LoadJS default DOM insertion mechanism (DOM `<head>`) ```javascript loadjs(['/path/to/foo.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { document.body.appendChild(scriptEl); /* return `false` to bypass default DOM insertion mechanism */ return false; } }); ``` 1. Use bundle ids in error callback ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk'); // wait for multiple depdendencies loadjs.ready(['foo', 'bar', 'thunk'], { success: function() { // foo.js & bar.js & thunkor.js & thunky.js loaded }, error: function(depsNotFound) { if (depsNotFound.indexOf('foo') > -1) {}; // foo failed if (depsNotFound.indexOf('bar') > -1) {}; // bar failed if (depsNotFound.indexOf('thunk') > -1) {}; // thunk failed } }); ``` 1. Use .done() for more control ```javascript loadjs.ready(['dependency1', 'dependency2'], function() { /* run code after dependencies have been met */ }); function fn1() { loadjs.done('dependency1'); } function fn2() { loadjs.done('dependency2'); } ``` 1. Reset dependency trackers ```javascript loadjs.reset(); ``` 1. Implement a require-like dependency manager ```javascript var bundles = { 'bundleA': ['/file1.js', '/file2.js'], 'bundleB': ['/file3.js', '/file4.js'] }; function require(bundleIds, callbackFn) { bundleIds.forEach(function(bundleId) { if (!loadjs.isDefined(bundleId)) loadjs(bundles[bundleId], bundleId); }); loadjs.ready(bundleIds, callbackFn); } require(['bundleA'], function() { /* bundleA loaded */ }); require(['bundleB'], function() { /* bundleB loaded */ }); require(['bundleA', 'bundleB'], function() { /* bundleA and bundleB loaded */ }); ``` ## Directory structure <pre> loadjs/ ├── dist │   ├── loadjs.js │   ├── loadjs.min.js │   └── loadjs.umd.js ├── examples ├── gulpfile.js ├── LICENSE.txt ├── package.json ├── README.md ├── src │   └── loadjs.js ├── test └── umd-templates </pre> ## Development Quickstart 1. Install dependencies * [nodejs](http://nodejs.org/) * [npm](https://www.npmjs.org/) * http-server (via npm) 1. Clone repository ```bash $ git clone [email protected]:muicss/loadjs.git $ cd loadjs ``` 1. Install node dependencies using npm ```bash $ npm install ``` 1. Build examples ```bash $ npm run build-examples ``` To view the examples you can use any static file server. To use the `nodejs` http-server module: ```bash $ npm install http-server $ npm run http-server -- -p 3000 ``` Then visit [http://localhost:3000/examples](http://localhost:3000/examples) 1. Build distribution files ```bash $ npm run build-dist ``` The files will be located in the `dist` directory. 1. Run tests To run the browser tests first build the `loadjs` library: ```bash $ npm run build-tests ``` Then visit [http://localhost:3000/test](http://localhost:3000/test) 1. Build all files ```bash $ npm run build-all ``` <MSG> Update README.md <DFF> @@ -9,7 +9,7 @@ LoadJS is a tiny async loader for modern browsers (711 bytes). ## Introduction -LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript and CSS files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.js) in your &lt;html&gt; (possibly in the &lt;head&gt; tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload. +LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript and CSS files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.min.js) in your &lt;html&gt; (possibly in the &lt;head&gt; tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload. LoadJS is based on the excellent [$script](https://github.com/ded/script.js) library by [Dustin Diaz](https://github.com/ded). We kept the behavior of the library the same but we re-wrote the code from scratch to add support for success/error callbacks and to optimize the library for modern browsers. LoadJS is 711 bytes (minified + gzipped).
1
Update README.md
1
.md
md
mit
muicss/loadjs
10068124
<NME> README.md <BEF> # LoadJS <img src="https://www.muicss.com/static/images/loadjs.svg" width="250px"> LoadJS is a tiny async loader for modern browsers (899 bytes). [![Dependency Status](https://david-dm.org/muicss/loadjs.svg)](https://david-dm.org/muicss/loadjs) [![devDependency Status](https://david-dm.org/muicss/loadjs/dev-status.svg)](https://david-dm.org/muicss/loadjs?type=dev) ## Introduction LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript and CSS files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.js) in your &lt;html&gt; (possibly in the &lt;head&gt; tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload. LoadJS is based on the excellent [$script](https://github.com/ded/script.js) library by [Dustin Diaz](https://github.com/ded). We kept the behavior of the library the same but we re-wrote the code from scratch to add support for success/error callbacks and to optimize the library for modern browsers. LoadJS is 711 bytes (minified + gzipped). Here's an example of what you can do with LoadJS: ```html <script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script> <script> // define a dependency bundle and execute code when it loads loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); </script> ``` You can also use more advanced syntax for more options: ```html <script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script> <script> // define a dependency bundle with advanced options loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { before: function(path, scriptEl) { /* execute code before fetch */ }, async: true, // load files synchronously or asynchronously (default: true) numRetries: 3 // see caveats about using numRetries with async:false (default: 0), returnPromise: false // return Promise object (default: false) }); loadjs.ready('foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(depsNotFound) { /* foobar bundle load failed */ }, }); </script> ``` The latest version of LoadJS can be found in the `dist/` directory in this repository: * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js) (for development) * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js) (for production) It's also available from these public CDNs: * UNPKG * [https://unpkg.com/[email protected]/dist/loadjs.js](https://unpkg.com/[email protected]/dist/loadjs.js) (for development) * [https://unpkg.com/[email protected]/dist/loadjs.min.js](https://unpkg.com/[email protected]/dist/loadjs.min.js) (for production) * CDNJS * [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js) (for development) * [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js) (for production) You can also use it as a CJS or AMD module: ```bash $ npm install --save loadjs ``` ```javascript var loadjs = require('loadjs'); loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); ``` ## Browser Support * IE9+ (`async: false` support only works in IE10+) * Opera 12+ * Safari 5+ * Chrome * Firefox * iOS 6+ * Android 4.4+ LoadJS also detects script load failures from AdBlock Plus and Ghostery in: * Safari * Chrome Note: LoadJS treats empty CSS files as load failures in IE9-11 and uses `rel="preload"` to load CSS files in Edge (to get around lack of support for onerror events on `<link rel="stylesheet">` tags) ## Documentation 1. Load a single file ```javascript loadjs('/path/to/foo.js', function() { /* foo.js loaded */ }); ``` 1. Fetch files in parallel and load them asynchronously ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], function() { /* foo.js and bar.js loaded */ }); ``` 1. Fetch JavaScript, CSS and image files ```javascript loadjs(['/path/to/foo.css', '/path/to/bar.png', 'path/to/thunk.js'], function() { /* foo.css, bar.png and thunk.js loaded */ }); ``` 1. Force treat file as CSS stylesheet ```javascript loadjs(['css!/path/to/cssfile.custom'], function() { /* cssfile.custom loaded as stylesheet */ }); ``` 1. Force treat file as image ```javascript loadjs(['img!/path/to/image.custom'], function() { /* image.custom loaded */ }); ``` 1. Add a bundle id ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }); ``` 1. Use .ready() to define bundles and callbacks separately ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); ``` 1. Use multiple bundles in .ready() dependency lists ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs(['/path/to/bar1.js', '/path/to/bar2.js'], 'bar'); loadjs.ready(['foo', 'bar'], function() { /* foo.js & bar1.js & bar2.js loaded */ }); ``` 1. Chain .ready() together ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs .ready('foo', function() { /* foo.js loaded */ }) .ready('bar', function() { /* bar.js loaded */ }); ``` 1. Use Promises to register callbacks ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], {returnPromise: true}) .then(function() { /* foo.js & bar.js loaded */ }) .catch(function(pathsNotFound) { /* at least one didn't load */ }); ``` 1. Check if bundle has already been defined ```javascript if (!loadjs.isDefined('foobar')) { loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }); } ``` 1. Fetch files in parallel and load them in series ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() { /* foo.js and bar.js loaded in series */ }, async: false }); ``` 1. Add an error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ } }); ``` 1. Retry files before calling the error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ }, numRetries: 3 }); // NOTE: Using `numRetries` with `async: false` can cause files to load out-of-sync on retries ``` 1. Execute a callback before script tags are embedded ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { /* called for each script node before being embedded */ if (path === '/path/to/foo.js') scriptEl.crossOrigin = true; } }); ``` 1. Bypass LoadJS default DOM insertion mechanism (DOM `<head>`) ```javascript loadjs(['/path/to/foo.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { document.body.appendChild(scriptEl); /* return `false` to bypass default DOM insertion mechanism */ return false; } }); ``` 1. Use bundle ids in error callback ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk'); // wait for multiple depdendencies loadjs.ready(['foo', 'bar', 'thunk'], { success: function() { // foo.js & bar.js & thunkor.js & thunky.js loaded }, error: function(depsNotFound) { if (depsNotFound.indexOf('foo') > -1) {}; // foo failed if (depsNotFound.indexOf('bar') > -1) {}; // bar failed if (depsNotFound.indexOf('thunk') > -1) {}; // thunk failed } }); ``` 1. Use .done() for more control ```javascript loadjs.ready(['dependency1', 'dependency2'], function() { /* run code after dependencies have been met */ }); function fn1() { loadjs.done('dependency1'); } function fn2() { loadjs.done('dependency2'); } ``` 1. Reset dependency trackers ```javascript loadjs.reset(); ``` 1. Implement a require-like dependency manager ```javascript var bundles = { 'bundleA': ['/file1.js', '/file2.js'], 'bundleB': ['/file3.js', '/file4.js'] }; function require(bundleIds, callbackFn) { bundleIds.forEach(function(bundleId) { if (!loadjs.isDefined(bundleId)) loadjs(bundles[bundleId], bundleId); }); loadjs.ready(bundleIds, callbackFn); } require(['bundleA'], function() { /* bundleA loaded */ }); require(['bundleB'], function() { /* bundleB loaded */ }); require(['bundleA', 'bundleB'], function() { /* bundleA and bundleB loaded */ }); ``` ## Directory structure <pre> loadjs/ ├── dist │   ├── loadjs.js │   ├── loadjs.min.js │   └── loadjs.umd.js ├── examples ├── gulpfile.js ├── LICENSE.txt ├── package.json ├── README.md ├── src │   └── loadjs.js ├── test └── umd-templates </pre> ## Development Quickstart 1. Install dependencies * [nodejs](http://nodejs.org/) * [npm](https://www.npmjs.org/) * http-server (via npm) 1. Clone repository ```bash $ git clone [email protected]:muicss/loadjs.git $ cd loadjs ``` 1. Install node dependencies using npm ```bash $ npm install ``` 1. Build examples ```bash $ npm run build-examples ``` To view the examples you can use any static file server. To use the `nodejs` http-server module: ```bash $ npm install http-server $ npm run http-server -- -p 3000 ``` Then visit [http://localhost:3000/examples](http://localhost:3000/examples) 1. Build distribution files ```bash $ npm run build-dist ``` The files will be located in the `dist` directory. 1. Run tests To run the browser tests first build the `loadjs` library: ```bash $ npm run build-tests ``` Then visit [http://localhost:3000/test](http://localhost:3000/test) 1. Build all files ```bash $ npm run build-all ``` <MSG> Update README.md <DFF> @@ -9,7 +9,7 @@ LoadJS is a tiny async loader for modern browsers (711 bytes). ## Introduction -LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript and CSS files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.js) in your &lt;html&gt; (possibly in the &lt;head&gt; tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload. +LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript and CSS files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.min.js) in your &lt;html&gt; (possibly in the &lt;head&gt; tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload. LoadJS is based on the excellent [$script](https://github.com/ded/script.js) library by [Dustin Diaz](https://github.com/ded). We kept the behavior of the library the same but we re-wrote the code from scratch to add support for success/error callbacks and to optimize the library for modern browsers. LoadJS is 711 bytes (minified + gzipped).
1
Update README.md
1
.md
md
mit
muicss/loadjs
10068125
<NME> tr.js <BEF> ADDFILE <MSG> Merge pull request #295 from ozanh/master i18n: Add Turkish locale <DFF> @@ -0,0 +1,47 @@ +(function(jsGrid) { + + jsGrid.locales.tr = { + grid: { + noDataContent: "Kayıt Bulunamadı", + deleteConfirm: "Emin misiniz ?", + pagerFormat: "Sayfalar: {first} {prev} {pages} {next} {last} &nbsp;&nbsp; {pageIndex} / {pageCount}", + pagePrevText: "<", + pageNextText: ">", + pageFirstText: "<<", + pageLastText: ">>", + loadMessage: "Lütfen bekleyiniz...", + invalidMessage: "Geçersiz veri girişi !" + }, + + loadIndicator: { + message: "Yükleniyor..." + }, + + fields: { + control: { + searchModeButtonTooltip: "Arama moduna geç", + insertModeButtonTooltip: "Yeni kayıt moduna geç", + editButtonTooltip: "Değiştir", + deleteButtonTooltip: "Sil", + searchButtonTooltip: "Bul", + clearFilterButtonTooltip: "Filtreyi temizle", + insertButtonTooltip: "Ekle", + updateButtonTooltip: "Güncelle", + cancelEditButtonTooltip: "Güncelleme iptali" + } + }, + + validators: { + required: { message: "Gerekli alandır" }, + rangeLength: { message: "Alan değerinin uzunluğu tanımlanan aralık dışındadır" }, + minLength: { message: "Alan değeri çok kısadır" }, + maxLength: { message: "Alan değeri çok uzundur" }, + pattern: { message: "Alan değeri tanımlanan şablon ile eşleşmiyor" }, + range: { message: "Alan değeri tanımlı aralığın dışındadır" }, + min: { message: "Alan değeri çok küçüktür" }, + max: { message: "Alan değeri çok büyüktür" } + } + }; + +}(jsGrid, jQuery)); +
47
Merge pull request #295 from ozanh/master
0
.js
js
mit
tabalinas/jsgrid
10068126
<NME> tr.js <BEF> ADDFILE <MSG> Merge pull request #295 from ozanh/master i18n: Add Turkish locale <DFF> @@ -0,0 +1,47 @@ +(function(jsGrid) { + + jsGrid.locales.tr = { + grid: { + noDataContent: "Kayıt Bulunamadı", + deleteConfirm: "Emin misiniz ?", + pagerFormat: "Sayfalar: {first} {prev} {pages} {next} {last} &nbsp;&nbsp; {pageIndex} / {pageCount}", + pagePrevText: "<", + pageNextText: ">", + pageFirstText: "<<", + pageLastText: ">>", + loadMessage: "Lütfen bekleyiniz...", + invalidMessage: "Geçersiz veri girişi !" + }, + + loadIndicator: { + message: "Yükleniyor..." + }, + + fields: { + control: { + searchModeButtonTooltip: "Arama moduna geç", + insertModeButtonTooltip: "Yeni kayıt moduna geç", + editButtonTooltip: "Değiştir", + deleteButtonTooltip: "Sil", + searchButtonTooltip: "Bul", + clearFilterButtonTooltip: "Filtreyi temizle", + insertButtonTooltip: "Ekle", + updateButtonTooltip: "Güncelle", + cancelEditButtonTooltip: "Güncelleme iptali" + } + }, + + validators: { + required: { message: "Gerekli alandır" }, + rangeLength: { message: "Alan değerinin uzunluğu tanımlanan aralık dışındadır" }, + minLength: { message: "Alan değeri çok kısadır" }, + maxLength: { message: "Alan değeri çok uzundur" }, + pattern: { message: "Alan değeri tanımlanan şablon ile eşleşmiyor" }, + range: { message: "Alan değeri tanımlı aralığın dışındadır" }, + min: { message: "Alan değeri çok küçüktür" }, + max: { message: "Alan değeri çok büyüktür" } + } + }; + +}(jsGrid, jQuery)); +
47
Merge pull request #295 from ozanh/master
0
.js
js
mit
tabalinas/jsgrid
10068127
<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)); } OnOptionChanged(e); } protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) { base.OnPropertyChanged(change); base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Update Avalonia <DFF> @@ -204,7 +204,7 @@ namespace AvaloniaEdit OnOptionChanged(e); } - protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change);
1
Update Avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068128
<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)); } OnOptionChanged(e); } protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) { base.OnPropertyChanged(change); base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Update Avalonia <DFF> @@ -204,7 +204,7 @@ namespace AvaloniaEdit OnOptionChanged(e); } - protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change);
1
Update Avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068129
<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)); } OnOptionChanged(e); } protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) { base.OnPropertyChanged(change); base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Update Avalonia <DFF> @@ -204,7 +204,7 @@ namespace AvaloniaEdit OnOptionChanged(e); } - protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change);
1
Update Avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068130
<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)); } OnOptionChanged(e); } protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) { base.OnPropertyChanged(change); base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Update Avalonia <DFF> @@ -204,7 +204,7 @@ namespace AvaloniaEdit OnOptionChanged(e); } - protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change);
1
Update Avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068131
<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)); } OnOptionChanged(e); } protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) { base.OnPropertyChanged(change); base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Update Avalonia <DFF> @@ -204,7 +204,7 @@ namespace AvaloniaEdit OnOptionChanged(e); } - protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change);
1
Update Avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068132
<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)); } OnOptionChanged(e); } protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) { base.OnPropertyChanged(change); base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Update Avalonia <DFF> @@ -204,7 +204,7 @@ namespace AvaloniaEdit OnOptionChanged(e); } - protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change);
1
Update Avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068133
<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)); } OnOptionChanged(e); } protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) { base.OnPropertyChanged(change); base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Update Avalonia <DFF> @@ -204,7 +204,7 @@ namespace AvaloniaEdit OnOptionChanged(e); } - protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change);
1
Update Avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068134
<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)); } OnOptionChanged(e); } protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) { base.OnPropertyChanged(change); base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Update Avalonia <DFF> @@ -204,7 +204,7 @@ namespace AvaloniaEdit OnOptionChanged(e); } - protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change);
1
Update Avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068135
<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)); } OnOptionChanged(e); } protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) { base.OnPropertyChanged(change); base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Update Avalonia <DFF> @@ -204,7 +204,7 @@ namespace AvaloniaEdit OnOptionChanged(e); } - protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change);
1
Update Avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068136
<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)); } OnOptionChanged(e); } protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) { base.OnPropertyChanged(change); base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Update Avalonia <DFF> @@ -204,7 +204,7 @@ namespace AvaloniaEdit OnOptionChanged(e); } - protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change);
1
Update Avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068137
<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)); } OnOptionChanged(e); } protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) { base.OnPropertyChanged(change); base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Update Avalonia <DFF> @@ -204,7 +204,7 @@ namespace AvaloniaEdit OnOptionChanged(e); } - protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change);
1
Update Avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068138
<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)); } OnOptionChanged(e); } protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) { base.OnPropertyChanged(change); base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Update Avalonia <DFF> @@ -204,7 +204,7 @@ namespace AvaloniaEdit OnOptionChanged(e); } - protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change);
1
Update Avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068139
<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)); } OnOptionChanged(e); } protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) { base.OnPropertyChanged(change); base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Update Avalonia <DFF> @@ -204,7 +204,7 @@ namespace AvaloniaEdit OnOptionChanged(e); } - protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change);
1
Update Avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068140
<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)); } OnOptionChanged(e); } protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) { base.OnPropertyChanged(change); base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Update Avalonia <DFF> @@ -204,7 +204,7 @@ namespace AvaloniaEdit OnOptionChanged(e); } - protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change);
1
Update Avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068141
<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)); } OnOptionChanged(e); } protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) { base.OnPropertyChanged(change); base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Update Avalonia <DFF> @@ -204,7 +204,7 @@ namespace AvaloniaEdit OnOptionChanged(e); } - protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change);
1
Update Avalonia
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068142
<NME> TextView.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Rendering { /// <summary> /// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>. /// /// This is the heart of the text editor, this class controls the text rendering process. /// /// Taken as a standalone control, it's a text viewer without any editing capability. /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent, ILogicalScrollable { private EventHandler _scrollInvalidated; #region Constructor static TextView() { ClipToBoundsProperty.OverrideDefaultValue<TextView>(true); FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; /// <summary> /// Creates a new TextView instance. /// </summary> public TextView() { Services.AddService(this); TextLayer = new TextLayer(this); _elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed); _lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed); _backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed); _columnRulerRenderer = new ColumnRulerRenderer(this); _currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this); Options = new TextEditorOptions(); Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators Layers = new LayerCollection(this); InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace); _hoverLogic = new PointerHoverLogic(this); _hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent); _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } #endregion #region Document Property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = AvaloniaProperty.Register<TextView, TextDocument>("Document"); private TextDocument _document; private HeightTree _heightTree; /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } internal double FontSize { get => GetValue(TemplatedControl.FontSizeProperty); set => SetValue(TemplatedControl.FontSizeProperty, value); } internal FontFamily FontFamily { get => GetValue(TemplatedControl.FontFamilyProperty); set => SetValue(TemplatedControl.FontFamilyProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { _heightTree.Dispose(); _heightTree = null; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options 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); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); RemoveInlineObjects(visualLine); } #endregion #region Get(OrConstruct)VisualLine /// <summary> /// Gets the visual line that contains the document line with the specified number. /// Returns null if the document line is outside the visible range. /// </summary> public VisualLine GetVisualLine(int documentLineNumber) { // TODO: EnsureVisualLines() ? foreach (var visualLine in _allVisualLines) { Debug.Assert(visualLine.IsDisposed == false); var start = visualLine.FirstDocumentLine.LineNumber; var end = visualLine.LastDocumentLine.LineNumber; if (documentLineNumber >= start && documentLineNumber <= end) return visualLine; } return null; } /// <summary> /// Gets the visual line that contains the document line with the specified number. /// If that line is outside the visible range, a new VisualLine for that document line is constructed. /// </summary> public VisualLine GetOrConstructVisualLine(DocumentLine documentLine) { if (documentLine == null) throw new ArgumentNullException("documentLine"); if (!this.Document.Lines.Contains(documentLine)) throw new InvalidOperationException("Line belongs to wrong document"); VerifyAccess(); VisualLine l = GetVisualLine(documentLine.LineNumber); if (l == null) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); while (_heightTree.GetIsCollapsed(documentLine.LineNumber)) { documentLine = documentLine.PreviousLine; } l = BuildVisualLine(documentLine, globalTextRunProperties, paragraphProperties, _elementGenerators.ToArray(), _lineTransformers.ToArray(), _lastAvailableSize); _allVisualLines.Add(l); // update all visual top values (building the line might have changed visual top of other lines due to word wrapping) foreach (var line in _allVisualLines) { line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine); } } return l; } #endregion #region Visual Lines (fields and properties) private List<VisualLine> _allVisualLines = new List<VisualLine>(); private ReadOnlyCollection<VisualLine> _visibleVisualLines; private double _clippedPixelsOnTop; private List<VisualLine> _newVisualLines; /// <summary> /// Gets the currently visible visual lines. /// </summary> /// <exception cref="VisualLinesInvalidException"> /// Gets thrown if there are invalid visual lines when this property is accessed. /// You can use the <see cref="VisualLinesValid"/> property to check for this case, /// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines /// when they are invalid. /// </exception> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public ReadOnlyCollection<VisualLine> VisualLines { get { if (_visibleVisualLines == null) throw new VisualLinesInvalidException(); return _visibleVisualLines; } } /// <summary> /// Gets whether the visual lines are valid. /// Will return false after a call to Redraw(). /// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/> /// if this property is <c>false</c>. /// </summary> public bool VisualLinesValid => _visibleVisualLines != null; /// <summary> /// Occurs when the TextView is about to be measured and will regenerate its visual lines. /// This event may be used to mark visual lines as invalid that would otherwise be reused. /// </summary> public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting; /// <summary> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); maxWidth += AdditionalHorizontalScrollAmount; var heightTreeHeight = DocumentHeight; var options = Options; double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight); double extraHeightToAllowScrollBelowDocument = 0; if (options.AllowScrollBelowDocument) { if (!double.IsInfinity(_scrollViewport.Height)) { // HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after // scrolling to the very bottom. var minVisibleDocumentHeight = DefaultLineHeight; // increase the extend height to allow scrolling below the document extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight; } } TextLayer.SetVisualLines(_visibleVisualLines); SetScrollData(availableSize, new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument), _scrollOffset); VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight); } /// <summary> /// Build all VisualLines in the visible range. /// </summary> /// <returns>Width the longest line</returns> private double CreateAndMeasureVisualLines(Size availableSize) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); //Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset); var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y); // number of pixels clipped from the first visual line(s) _clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView); // clippedPixelsOnTop should be >= 0, except for floating point inaccurracy. Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon); _newVisualLines = new List<VisualLine>(); VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView)); var elementGeneratorsArray = _elementGenerators.ToArray(); var lineTransformersArray = _lineTransformers.ToArray(); var nextLine = firstLineInView; double maxWidth = 0; var yPos = -_clippedPixelsOnTop; while (yPos < availableSize.Height && nextLine != null) { var visualLine = GetVisualLine(nextLine.LineNumber) ?? BuildVisualLine(nextLine, globalTextRunProperties, paragraphProperties, elementGeneratorsArray, lineTransformersArray, availableSize); visualLine.VisualTop = _scrollOffset.Y + yPos; nextLine = visualLine.LastDocumentLine.NextLine; yPos += visualLine.Height; foreach (var textLine in visualLine.TextLines) { if (textLine.WidthIncludingTrailingWhitespace > maxWidth) maxWidth = textLine.WidthIncludingTrailingWhitespace; } _newVisualLines.Add(visualLine); } foreach (var line in _allVisualLines) { Debug.Assert(line.IsDisposed == false); if (!_newVisualLines.Contains(line)) DisposeVisualLine(line); } _allVisualLines = _newVisualLines; // visibleVisualLines = readonly copy of visual lines _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray()); _newVisualLines = null; if (_allVisualLines.Any(line => line.IsDisposed)) { throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" + "This can happen when Redraw() is called during measure for lines " + "that are already constructed."); } return maxWidth; } #endregion #region BuildVisualLine private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<IVisualLineTransformer> lineTransformersArray, Size availableSize) { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); //Debug.WriteLine("Building line " + documentLine.LineNumber); VisualLine visualLine = new VisualLine(this, documentLine); VisualLineTextSource textSource = new VisualLineTextSource(visualLine) { Document = _document, GlobalTextRunProperties = globalTextRunProperties, TextView = this }; visualLine.ConstructVisualElements(textSource, elementGeneratorsArray); if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine) { // Check whether the lines are collapsed correctly: double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine); double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine); if (!firstLinePos.IsClose(lastLinePos)) { for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++) { if (!_heightTree.GetIsCollapsed(i)) throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed."); } throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?"); } } visualLine.RunTransformers(textSource, lineTransformersArray); // now construct textLines: TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( textSource, textOffset, availableSize.Width, paragraphProperties, lastLineBreak ); textLines.Add(textLine); textOffset += textLine.Length; // exit loop so that we don't do the indentation calculation if there's only a single line if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker) break; if (paragraphProperties.firstLineInParagraph) { paragraphProperties.firstLineInParagraph = false; TextEditorOptions options = this.Options; double indentation = 0; if (options.InheritWordWrapIndentation) { // determine indentation for next line: int indentVisualColumn = GetIndentationVisualColumn(visualLine); if (indentVisualColumn > 0 && indentVisualColumn < textOffset) { indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0)); } } indentation += options.WordWrapIndentation; // apply the calculated indentation unless it's more than half of the text editor size: if (indentation > 0 && indentation * 2 < availableSize.Width) paragraphProperties.indent = indentation; } lastLineBreak = textLine.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var element = visualLine.Elements[elementIndex]; while (element.IsWhitespace(column)) { column++; if (column == element.VisualColumn + element.VisualLength) { elementIndex++; if (elementIndex == visualLine.Elements.Count) break; element = visualLine.Elements[elementIndex]; } } return column; } #endregion #region Arrange /// <summary> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } startVc = element.VisualColumn; length = element.DocumentLength; currentBrush = element.BackgroundBrush; } else { length += element.VisualLength; } } if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> /// Gets the vertical scroll offset. /// </summary> public double VerticalOffset => _scrollOffset.Y; /// <summary> /// Gets the scroll offset; /// </summary> public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); } } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation. /// <summary> /// Gets the width of a 'wide space' (the space width used for calculating the tab size). /// </summary> /// <remarks> /// This is the width of an 'x' in the current font. /// We do not measure the width of an actual space as that would lead to tiny tabs in /// some proportional fonts. /// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width. /// </remarks> public double WideSpaceWidth { get { CalculateDefaultTextMetrics(); return _wideSpaceWidth; } } /// <summary> /// Gets the default line height. This is the height of an empty line or a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different line height. /// </summary> public double DefaultLineHeight { get { CalculateDefaultTextMetrics(); return _defaultLineHeight; } } /// <summary> /// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/> /// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different baseline. /// </summary> public double DefaultBaseline { get { CalculateDefaultTextMetrics(); return _defaultBaseline; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); var line = _formatter.FormatLine( new SimpleTextSource("x", textRunProperties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties }, null); _wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace); _defaultBaseline = Math.Max(1, line.Baseline); _defaultLineHeight = Math.Max(1, line.Height); } else { _wideSpaceWidth = FontSize / 2; _defaultBaseline = FontSize; _defaultLineHeight = FontSize + 3; } // Update heightTree.DefaultLineHeight, if a document is loaded. if (_heightTree != null) _heightTree.DefaultLineHeight = _defaultLineHeight; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(e); } } #endregion #region Getting elements from Visual Position /// <summary> /// Gets the visual line at the specified document position (relative to start of document). /// Returns null if there is no visual line for the position (e.g. the position is outside the visible /// text area). /// </summary> public VisualLine GetVisualLineFromVisualTop(double visualTop) { // TODO: change this method to also work outside the visible range - // required to make GetPosition work as expected! EnsureVisualLines(); foreach (var vl in VisualLines) { if (visualTop < vl.VisualTop) continue; if (visualTop < vl.VisualTop + vl.Height) return vl; } return null; } /// <summary> /// Gets the visual top position (relative to start of document) from a document line number. /// </summary> public double GetVisualTopByDocumentLine(int line) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) continue; return element; } } return null; } #endregion #region Visual Position <-> TextViewPosition /// <summary> /// Gets the visual position from a text view position. /// </summary> /// <param name="position">The text view position.</param> /// <param name="yPositionMode">The mode how to retrieve the Y position.</param> /// <returns>The position in device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is within a character, it is rounded to the next character boundary. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPosition(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is inside a character, the position in front of the character is returned. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPositionFloor(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <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 pointe 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); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #endregion /// <summary> /// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden /// and not used to start the generation of a <see cref="VisualLine"/>. /// </summary> /// <remarks> /// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span /// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding /// <see cref="VisualLineElementGenerator"/>. /// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>. /// /// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines /// N+1 to M. Do not collapse line N itself. /// /// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the /// <see cref="CollapsedLineSection"/> returned from this method. /// </remarks> public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.CollapseText(start, end); } /// <summary> /// Gets the height of the document. /// </summary> public double DocumentHeight => _heightTree?.TotalHeight ?? 0; /// <summary> /// Gets the document line at the specified visual position. /// </summary> public DocumentLine GetDocumentLineByVisualTop(double visualTop) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetLineByVisualPosition(visualTop); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge pull request #64 from siegfriedpammer/dev/siegfriedpammer/folding-element-fixes Folding element fixes <DFF> @@ -1316,6 +1316,8 @@ namespace AvaloniaEdit.Rendering internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { + // this is necessary so hit-testing works properly and events get tunneled to the TextView. + drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer)
2
Merge pull request #64 from siegfriedpammer/dev/siegfriedpammer/folding-element-fixes
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068143
<NME> TextView.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Rendering { /// <summary> /// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>. /// /// This is the heart of the text editor, this class controls the text rendering process. /// /// Taken as a standalone control, it's a text viewer without any editing capability. /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent, ILogicalScrollable { private EventHandler _scrollInvalidated; #region Constructor static TextView() { ClipToBoundsProperty.OverrideDefaultValue<TextView>(true); FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; /// <summary> /// Creates a new TextView instance. /// </summary> public TextView() { Services.AddService(this); TextLayer = new TextLayer(this); _elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed); _lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed); _backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed); _columnRulerRenderer = new ColumnRulerRenderer(this); _currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this); Options = new TextEditorOptions(); Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators Layers = new LayerCollection(this); InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace); _hoverLogic = new PointerHoverLogic(this); _hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent); _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } #endregion #region Document Property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = AvaloniaProperty.Register<TextView, TextDocument>("Document"); private TextDocument _document; private HeightTree _heightTree; /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } internal double FontSize { get => GetValue(TemplatedControl.FontSizeProperty); set => SetValue(TemplatedControl.FontSizeProperty, value); } internal FontFamily FontFamily { get => GetValue(TemplatedControl.FontFamilyProperty); set => SetValue(TemplatedControl.FontFamilyProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { _heightTree.Dispose(); _heightTree = null; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options 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); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); RemoveInlineObjects(visualLine); } #endregion #region Get(OrConstruct)VisualLine /// <summary> /// Gets the visual line that contains the document line with the specified number. /// Returns null if the document line is outside the visible range. /// </summary> public VisualLine GetVisualLine(int documentLineNumber) { // TODO: EnsureVisualLines() ? foreach (var visualLine in _allVisualLines) { Debug.Assert(visualLine.IsDisposed == false); var start = visualLine.FirstDocumentLine.LineNumber; var end = visualLine.LastDocumentLine.LineNumber; if (documentLineNumber >= start && documentLineNumber <= end) return visualLine; } return null; } /// <summary> /// Gets the visual line that contains the document line with the specified number. /// If that line is outside the visible range, a new VisualLine for that document line is constructed. /// </summary> public VisualLine GetOrConstructVisualLine(DocumentLine documentLine) { if (documentLine == null) throw new ArgumentNullException("documentLine"); if (!this.Document.Lines.Contains(documentLine)) throw new InvalidOperationException("Line belongs to wrong document"); VerifyAccess(); VisualLine l = GetVisualLine(documentLine.LineNumber); if (l == null) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); while (_heightTree.GetIsCollapsed(documentLine.LineNumber)) { documentLine = documentLine.PreviousLine; } l = BuildVisualLine(documentLine, globalTextRunProperties, paragraphProperties, _elementGenerators.ToArray(), _lineTransformers.ToArray(), _lastAvailableSize); _allVisualLines.Add(l); // update all visual top values (building the line might have changed visual top of other lines due to word wrapping) foreach (var line in _allVisualLines) { line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine); } } return l; } #endregion #region Visual Lines (fields and properties) private List<VisualLine> _allVisualLines = new List<VisualLine>(); private ReadOnlyCollection<VisualLine> _visibleVisualLines; private double _clippedPixelsOnTop; private List<VisualLine> _newVisualLines; /// <summary> /// Gets the currently visible visual lines. /// </summary> /// <exception cref="VisualLinesInvalidException"> /// Gets thrown if there are invalid visual lines when this property is accessed. /// You can use the <see cref="VisualLinesValid"/> property to check for this case, /// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines /// when they are invalid. /// </exception> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public ReadOnlyCollection<VisualLine> VisualLines { get { if (_visibleVisualLines == null) throw new VisualLinesInvalidException(); return _visibleVisualLines; } } /// <summary> /// Gets whether the visual lines are valid. /// Will return false after a call to Redraw(). /// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/> /// if this property is <c>false</c>. /// </summary> public bool VisualLinesValid => _visibleVisualLines != null; /// <summary> /// Occurs when the TextView is about to be measured and will regenerate its visual lines. /// This event may be used to mark visual lines as invalid that would otherwise be reused. /// </summary> public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting; /// <summary> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); maxWidth += AdditionalHorizontalScrollAmount; var heightTreeHeight = DocumentHeight; var options = Options; double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight); double extraHeightToAllowScrollBelowDocument = 0; if (options.AllowScrollBelowDocument) { if (!double.IsInfinity(_scrollViewport.Height)) { // HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after // scrolling to the very bottom. var minVisibleDocumentHeight = DefaultLineHeight; // increase the extend height to allow scrolling below the document extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight; } } TextLayer.SetVisualLines(_visibleVisualLines); SetScrollData(availableSize, new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument), _scrollOffset); VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight); } /// <summary> /// Build all VisualLines in the visible range. /// </summary> /// <returns>Width the longest line</returns> private double CreateAndMeasureVisualLines(Size availableSize) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); //Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset); var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y); // number of pixels clipped from the first visual line(s) _clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView); // clippedPixelsOnTop should be >= 0, except for floating point inaccurracy. Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon); _newVisualLines = new List<VisualLine>(); VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView)); var elementGeneratorsArray = _elementGenerators.ToArray(); var lineTransformersArray = _lineTransformers.ToArray(); var nextLine = firstLineInView; double maxWidth = 0; var yPos = -_clippedPixelsOnTop; while (yPos < availableSize.Height && nextLine != null) { var visualLine = GetVisualLine(nextLine.LineNumber) ?? BuildVisualLine(nextLine, globalTextRunProperties, paragraphProperties, elementGeneratorsArray, lineTransformersArray, availableSize); visualLine.VisualTop = _scrollOffset.Y + yPos; nextLine = visualLine.LastDocumentLine.NextLine; yPos += visualLine.Height; foreach (var textLine in visualLine.TextLines) { if (textLine.WidthIncludingTrailingWhitespace > maxWidth) maxWidth = textLine.WidthIncludingTrailingWhitespace; } _newVisualLines.Add(visualLine); } foreach (var line in _allVisualLines) { Debug.Assert(line.IsDisposed == false); if (!_newVisualLines.Contains(line)) DisposeVisualLine(line); } _allVisualLines = _newVisualLines; // visibleVisualLines = readonly copy of visual lines _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray()); _newVisualLines = null; if (_allVisualLines.Any(line => line.IsDisposed)) { throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" + "This can happen when Redraw() is called during measure for lines " + "that are already constructed."); } return maxWidth; } #endregion #region BuildVisualLine private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<IVisualLineTransformer> lineTransformersArray, Size availableSize) { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); //Debug.WriteLine("Building line " + documentLine.LineNumber); VisualLine visualLine = new VisualLine(this, documentLine); VisualLineTextSource textSource = new VisualLineTextSource(visualLine) { Document = _document, GlobalTextRunProperties = globalTextRunProperties, TextView = this }; visualLine.ConstructVisualElements(textSource, elementGeneratorsArray); if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine) { // Check whether the lines are collapsed correctly: double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine); double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine); if (!firstLinePos.IsClose(lastLinePos)) { for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++) { if (!_heightTree.GetIsCollapsed(i)) throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed."); } throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?"); } } visualLine.RunTransformers(textSource, lineTransformersArray); // now construct textLines: TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( textSource, textOffset, availableSize.Width, paragraphProperties, lastLineBreak ); textLines.Add(textLine); textOffset += textLine.Length; // exit loop so that we don't do the indentation calculation if there's only a single line if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker) break; if (paragraphProperties.firstLineInParagraph) { paragraphProperties.firstLineInParagraph = false; TextEditorOptions options = this.Options; double indentation = 0; if (options.InheritWordWrapIndentation) { // determine indentation for next line: int indentVisualColumn = GetIndentationVisualColumn(visualLine); if (indentVisualColumn > 0 && indentVisualColumn < textOffset) { indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0)); } } indentation += options.WordWrapIndentation; // apply the calculated indentation unless it's more than half of the text editor size: if (indentation > 0 && indentation * 2 < availableSize.Width) paragraphProperties.indent = indentation; } lastLineBreak = textLine.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var element = visualLine.Elements[elementIndex]; while (element.IsWhitespace(column)) { column++; if (column == element.VisualColumn + element.VisualLength) { elementIndex++; if (elementIndex == visualLine.Elements.Count) break; element = visualLine.Elements[elementIndex]; } } return column; } #endregion #region Arrange /// <summary> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } startVc = element.VisualColumn; length = element.DocumentLength; currentBrush = element.BackgroundBrush; } else { length += element.VisualLength; } } if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> /// Gets the vertical scroll offset. /// </summary> public double VerticalOffset => _scrollOffset.Y; /// <summary> /// Gets the scroll offset; /// </summary> public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); } } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation. /// <summary> /// Gets the width of a 'wide space' (the space width used for calculating the tab size). /// </summary> /// <remarks> /// This is the width of an 'x' in the current font. /// We do not measure the width of an actual space as that would lead to tiny tabs in /// some proportional fonts. /// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width. /// </remarks> public double WideSpaceWidth { get { CalculateDefaultTextMetrics(); return _wideSpaceWidth; } } /// <summary> /// Gets the default line height. This is the height of an empty line or a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different line height. /// </summary> public double DefaultLineHeight { get { CalculateDefaultTextMetrics(); return _defaultLineHeight; } } /// <summary> /// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/> /// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different baseline. /// </summary> public double DefaultBaseline { get { CalculateDefaultTextMetrics(); return _defaultBaseline; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); var line = _formatter.FormatLine( new SimpleTextSource("x", textRunProperties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties }, null); _wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace); _defaultBaseline = Math.Max(1, line.Baseline); _defaultLineHeight = Math.Max(1, line.Height); } else { _wideSpaceWidth = FontSize / 2; _defaultBaseline = FontSize; _defaultLineHeight = FontSize + 3; } // Update heightTree.DefaultLineHeight, if a document is loaded. if (_heightTree != null) _heightTree.DefaultLineHeight = _defaultLineHeight; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(e); } } #endregion #region Getting elements from Visual Position /// <summary> /// Gets the visual line at the specified document position (relative to start of document). /// Returns null if there is no visual line for the position (e.g. the position is outside the visible /// text area). /// </summary> public VisualLine GetVisualLineFromVisualTop(double visualTop) { // TODO: change this method to also work outside the visible range - // required to make GetPosition work as expected! EnsureVisualLines(); foreach (var vl in VisualLines) { if (visualTop < vl.VisualTop) continue; if (visualTop < vl.VisualTop + vl.Height) return vl; } return null; } /// <summary> /// Gets the visual top position (relative to start of document) from a document line number. /// </summary> public double GetVisualTopByDocumentLine(int line) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) continue; return element; } } return null; } #endregion #region Visual Position <-> TextViewPosition /// <summary> /// Gets the visual position from a text view position. /// </summary> /// <param name="position">The text view position.</param> /// <param name="yPositionMode">The mode how to retrieve the Y position.</param> /// <returns>The position in device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is within a character, it is rounded to the next character boundary. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPosition(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is inside a character, the position in front of the character is returned. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPositionFloor(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <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 pointe 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); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #endregion /// <summary> /// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden /// and not used to start the generation of a <see cref="VisualLine"/>. /// </summary> /// <remarks> /// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span /// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding /// <see cref="VisualLineElementGenerator"/>. /// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>. /// /// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines /// N+1 to M. Do not collapse line N itself. /// /// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the /// <see cref="CollapsedLineSection"/> returned from this method. /// </remarks> public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.CollapseText(start, end); } /// <summary> /// Gets the height of the document. /// </summary> public double DocumentHeight => _heightTree?.TotalHeight ?? 0; /// <summary> /// Gets the document line at the specified visual position. /// </summary> public DocumentLine GetDocumentLineByVisualTop(double visualTop) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetLineByVisualPosition(visualTop); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge pull request #64 from siegfriedpammer/dev/siegfriedpammer/folding-element-fixes Folding element fixes <DFF> @@ -1316,6 +1316,8 @@ namespace AvaloniaEdit.Rendering internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { + // this is necessary so hit-testing works properly and events get tunneled to the TextView. + drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer)
2
Merge pull request #64 from siegfriedpammer/dev/siegfriedpammer/folding-element-fixes
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068144
<NME> TextView.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Rendering { /// <summary> /// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>. /// /// This is the heart of the text editor, this class controls the text rendering process. /// /// Taken as a standalone control, it's a text viewer without any editing capability. /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent, ILogicalScrollable { private EventHandler _scrollInvalidated; #region Constructor static TextView() { ClipToBoundsProperty.OverrideDefaultValue<TextView>(true); FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; /// <summary> /// Creates a new TextView instance. /// </summary> public TextView() { Services.AddService(this); TextLayer = new TextLayer(this); _elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed); _lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed); _backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed); _columnRulerRenderer = new ColumnRulerRenderer(this); _currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this); Options = new TextEditorOptions(); Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators Layers = new LayerCollection(this); InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace); _hoverLogic = new PointerHoverLogic(this); _hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent); _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } #endregion #region Document Property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = AvaloniaProperty.Register<TextView, TextDocument>("Document"); private TextDocument _document; private HeightTree _heightTree; /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } internal double FontSize { get => GetValue(TemplatedControl.FontSizeProperty); set => SetValue(TemplatedControl.FontSizeProperty, value); } internal FontFamily FontFamily { get => GetValue(TemplatedControl.FontFamilyProperty); set => SetValue(TemplatedControl.FontFamilyProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { _heightTree.Dispose(); _heightTree = null; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options 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); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); RemoveInlineObjects(visualLine); } #endregion #region Get(OrConstruct)VisualLine /// <summary> /// Gets the visual line that contains the document line with the specified number. /// Returns null if the document line is outside the visible range. /// </summary> public VisualLine GetVisualLine(int documentLineNumber) { // TODO: EnsureVisualLines() ? foreach (var visualLine in _allVisualLines) { Debug.Assert(visualLine.IsDisposed == false); var start = visualLine.FirstDocumentLine.LineNumber; var end = visualLine.LastDocumentLine.LineNumber; if (documentLineNumber >= start && documentLineNumber <= end) return visualLine; } return null; } /// <summary> /// Gets the visual line that contains the document line with the specified number. /// If that line is outside the visible range, a new VisualLine for that document line is constructed. /// </summary> public VisualLine GetOrConstructVisualLine(DocumentLine documentLine) { if (documentLine == null) throw new ArgumentNullException("documentLine"); if (!this.Document.Lines.Contains(documentLine)) throw new InvalidOperationException("Line belongs to wrong document"); VerifyAccess(); VisualLine l = GetVisualLine(documentLine.LineNumber); if (l == null) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); while (_heightTree.GetIsCollapsed(documentLine.LineNumber)) { documentLine = documentLine.PreviousLine; } l = BuildVisualLine(documentLine, globalTextRunProperties, paragraphProperties, _elementGenerators.ToArray(), _lineTransformers.ToArray(), _lastAvailableSize); _allVisualLines.Add(l); // update all visual top values (building the line might have changed visual top of other lines due to word wrapping) foreach (var line in _allVisualLines) { line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine); } } return l; } #endregion #region Visual Lines (fields and properties) private List<VisualLine> _allVisualLines = new List<VisualLine>(); private ReadOnlyCollection<VisualLine> _visibleVisualLines; private double _clippedPixelsOnTop; private List<VisualLine> _newVisualLines; /// <summary> /// Gets the currently visible visual lines. /// </summary> /// <exception cref="VisualLinesInvalidException"> /// Gets thrown if there are invalid visual lines when this property is accessed. /// You can use the <see cref="VisualLinesValid"/> property to check for this case, /// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines /// when they are invalid. /// </exception> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public ReadOnlyCollection<VisualLine> VisualLines { get { if (_visibleVisualLines == null) throw new VisualLinesInvalidException(); return _visibleVisualLines; } } /// <summary> /// Gets whether the visual lines are valid. /// Will return false after a call to Redraw(). /// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/> /// if this property is <c>false</c>. /// </summary> public bool VisualLinesValid => _visibleVisualLines != null; /// <summary> /// Occurs when the TextView is about to be measured and will regenerate its visual lines. /// This event may be used to mark visual lines as invalid that would otherwise be reused. /// </summary> public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting; /// <summary> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); maxWidth += AdditionalHorizontalScrollAmount; var heightTreeHeight = DocumentHeight; var options = Options; double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight); double extraHeightToAllowScrollBelowDocument = 0; if (options.AllowScrollBelowDocument) { if (!double.IsInfinity(_scrollViewport.Height)) { // HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after // scrolling to the very bottom. var minVisibleDocumentHeight = DefaultLineHeight; // increase the extend height to allow scrolling below the document extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight; } } TextLayer.SetVisualLines(_visibleVisualLines); SetScrollData(availableSize, new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument), _scrollOffset); VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight); } /// <summary> /// Build all VisualLines in the visible range. /// </summary> /// <returns>Width the longest line</returns> private double CreateAndMeasureVisualLines(Size availableSize) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); //Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset); var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y); // number of pixels clipped from the first visual line(s) _clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView); // clippedPixelsOnTop should be >= 0, except for floating point inaccurracy. Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon); _newVisualLines = new List<VisualLine>(); VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView)); var elementGeneratorsArray = _elementGenerators.ToArray(); var lineTransformersArray = _lineTransformers.ToArray(); var nextLine = firstLineInView; double maxWidth = 0; var yPos = -_clippedPixelsOnTop; while (yPos < availableSize.Height && nextLine != null) { var visualLine = GetVisualLine(nextLine.LineNumber) ?? BuildVisualLine(nextLine, globalTextRunProperties, paragraphProperties, elementGeneratorsArray, lineTransformersArray, availableSize); visualLine.VisualTop = _scrollOffset.Y + yPos; nextLine = visualLine.LastDocumentLine.NextLine; yPos += visualLine.Height; foreach (var textLine in visualLine.TextLines) { if (textLine.WidthIncludingTrailingWhitespace > maxWidth) maxWidth = textLine.WidthIncludingTrailingWhitespace; } _newVisualLines.Add(visualLine); } foreach (var line in _allVisualLines) { Debug.Assert(line.IsDisposed == false); if (!_newVisualLines.Contains(line)) DisposeVisualLine(line); } _allVisualLines = _newVisualLines; // visibleVisualLines = readonly copy of visual lines _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray()); _newVisualLines = null; if (_allVisualLines.Any(line => line.IsDisposed)) { throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" + "This can happen when Redraw() is called during measure for lines " + "that are already constructed."); } return maxWidth; } #endregion #region BuildVisualLine private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<IVisualLineTransformer> lineTransformersArray, Size availableSize) { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); //Debug.WriteLine("Building line " + documentLine.LineNumber); VisualLine visualLine = new VisualLine(this, documentLine); VisualLineTextSource textSource = new VisualLineTextSource(visualLine) { Document = _document, GlobalTextRunProperties = globalTextRunProperties, TextView = this }; visualLine.ConstructVisualElements(textSource, elementGeneratorsArray); if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine) { // Check whether the lines are collapsed correctly: double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine); double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine); if (!firstLinePos.IsClose(lastLinePos)) { for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++) { if (!_heightTree.GetIsCollapsed(i)) throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed."); } throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?"); } } visualLine.RunTransformers(textSource, lineTransformersArray); // now construct textLines: TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( textSource, textOffset, availableSize.Width, paragraphProperties, lastLineBreak ); textLines.Add(textLine); textOffset += textLine.Length; // exit loop so that we don't do the indentation calculation if there's only a single line if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker) break; if (paragraphProperties.firstLineInParagraph) { paragraphProperties.firstLineInParagraph = false; TextEditorOptions options = this.Options; double indentation = 0; if (options.InheritWordWrapIndentation) { // determine indentation for next line: int indentVisualColumn = GetIndentationVisualColumn(visualLine); if (indentVisualColumn > 0 && indentVisualColumn < textOffset) { indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0)); } } indentation += options.WordWrapIndentation; // apply the calculated indentation unless it's more than half of the text editor size: if (indentation > 0 && indentation * 2 < availableSize.Width) paragraphProperties.indent = indentation; } lastLineBreak = textLine.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var element = visualLine.Elements[elementIndex]; while (element.IsWhitespace(column)) { column++; if (column == element.VisualColumn + element.VisualLength) { elementIndex++; if (elementIndex == visualLine.Elements.Count) break; element = visualLine.Elements[elementIndex]; } } return column; } #endregion #region Arrange /// <summary> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } startVc = element.VisualColumn; length = element.DocumentLength; currentBrush = element.BackgroundBrush; } else { length += element.VisualLength; } } if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> /// Gets the vertical scroll offset. /// </summary> public double VerticalOffset => _scrollOffset.Y; /// <summary> /// Gets the scroll offset; /// </summary> public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); } } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation. /// <summary> /// Gets the width of a 'wide space' (the space width used for calculating the tab size). /// </summary> /// <remarks> /// This is the width of an 'x' in the current font. /// We do not measure the width of an actual space as that would lead to tiny tabs in /// some proportional fonts. /// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width. /// </remarks> public double WideSpaceWidth { get { CalculateDefaultTextMetrics(); return _wideSpaceWidth; } } /// <summary> /// Gets the default line height. This is the height of an empty line or a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different line height. /// </summary> public double DefaultLineHeight { get { CalculateDefaultTextMetrics(); return _defaultLineHeight; } } /// <summary> /// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/> /// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different baseline. /// </summary> public double DefaultBaseline { get { CalculateDefaultTextMetrics(); return _defaultBaseline; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); var line = _formatter.FormatLine( new SimpleTextSource("x", textRunProperties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties }, null); _wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace); _defaultBaseline = Math.Max(1, line.Baseline); _defaultLineHeight = Math.Max(1, line.Height); } else { _wideSpaceWidth = FontSize / 2; _defaultBaseline = FontSize; _defaultLineHeight = FontSize + 3; } // Update heightTree.DefaultLineHeight, if a document is loaded. if (_heightTree != null) _heightTree.DefaultLineHeight = _defaultLineHeight; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(e); } } #endregion #region Getting elements from Visual Position /// <summary> /// Gets the visual line at the specified document position (relative to start of document). /// Returns null if there is no visual line for the position (e.g. the position is outside the visible /// text area). /// </summary> public VisualLine GetVisualLineFromVisualTop(double visualTop) { // TODO: change this method to also work outside the visible range - // required to make GetPosition work as expected! EnsureVisualLines(); foreach (var vl in VisualLines) { if (visualTop < vl.VisualTop) continue; if (visualTop < vl.VisualTop + vl.Height) return vl; } return null; } /// <summary> /// Gets the visual top position (relative to start of document) from a document line number. /// </summary> public double GetVisualTopByDocumentLine(int line) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) continue; return element; } } return null; } #endregion #region Visual Position <-> TextViewPosition /// <summary> /// Gets the visual position from a text view position. /// </summary> /// <param name="position">The text view position.</param> /// <param name="yPositionMode">The mode how to retrieve the Y position.</param> /// <returns>The position in device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is within a character, it is rounded to the next character boundary. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPosition(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is inside a character, the position in front of the character is returned. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPositionFloor(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <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 pointe 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); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #endregion /// <summary> /// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden /// and not used to start the generation of a <see cref="VisualLine"/>. /// </summary> /// <remarks> /// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span /// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding /// <see cref="VisualLineElementGenerator"/>. /// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>. /// /// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines /// N+1 to M. Do not collapse line N itself. /// /// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the /// <see cref="CollapsedLineSection"/> returned from this method. /// </remarks> public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.CollapseText(start, end); } /// <summary> /// Gets the height of the document. /// </summary> public double DocumentHeight => _heightTree?.TotalHeight ?? 0; /// <summary> /// Gets the document line at the specified visual position. /// </summary> public DocumentLine GetDocumentLineByVisualTop(double visualTop) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetLineByVisualPosition(visualTop); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge pull request #64 from siegfriedpammer/dev/siegfriedpammer/folding-element-fixes Folding element fixes <DFF> @@ -1316,6 +1316,8 @@ namespace AvaloniaEdit.Rendering internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { + // this is necessary so hit-testing works properly and events get tunneled to the TextView. + drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer)
2
Merge pull request #64 from siegfriedpammer/dev/siegfriedpammer/folding-element-fixes
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068145
<NME> TextView.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Rendering { /// <summary> /// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>. /// /// This is the heart of the text editor, this class controls the text rendering process. /// /// Taken as a standalone control, it's a text viewer without any editing capability. /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent, ILogicalScrollable { private EventHandler _scrollInvalidated; #region Constructor static TextView() { ClipToBoundsProperty.OverrideDefaultValue<TextView>(true); FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; /// <summary> /// Creates a new TextView instance. /// </summary> public TextView() { Services.AddService(this); TextLayer = new TextLayer(this); _elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed); _lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed); _backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed); _columnRulerRenderer = new ColumnRulerRenderer(this); _currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this); Options = new TextEditorOptions(); Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators Layers = new LayerCollection(this); InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace); _hoverLogic = new PointerHoverLogic(this); _hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent); _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } #endregion #region Document Property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = AvaloniaProperty.Register<TextView, TextDocument>("Document"); private TextDocument _document; private HeightTree _heightTree; /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } internal double FontSize { get => GetValue(TemplatedControl.FontSizeProperty); set => SetValue(TemplatedControl.FontSizeProperty, value); } internal FontFamily FontFamily { get => GetValue(TemplatedControl.FontFamilyProperty); set => SetValue(TemplatedControl.FontFamilyProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { _heightTree.Dispose(); _heightTree = null; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options 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); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); RemoveInlineObjects(visualLine); } #endregion #region Get(OrConstruct)VisualLine /// <summary> /// Gets the visual line that contains the document line with the specified number. /// Returns null if the document line is outside the visible range. /// </summary> public VisualLine GetVisualLine(int documentLineNumber) { // TODO: EnsureVisualLines() ? foreach (var visualLine in _allVisualLines) { Debug.Assert(visualLine.IsDisposed == false); var start = visualLine.FirstDocumentLine.LineNumber; var end = visualLine.LastDocumentLine.LineNumber; if (documentLineNumber >= start && documentLineNumber <= end) return visualLine; } return null; } /// <summary> /// Gets the visual line that contains the document line with the specified number. /// If that line is outside the visible range, a new VisualLine for that document line is constructed. /// </summary> public VisualLine GetOrConstructVisualLine(DocumentLine documentLine) { if (documentLine == null) throw new ArgumentNullException("documentLine"); if (!this.Document.Lines.Contains(documentLine)) throw new InvalidOperationException("Line belongs to wrong document"); VerifyAccess(); VisualLine l = GetVisualLine(documentLine.LineNumber); if (l == null) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); while (_heightTree.GetIsCollapsed(documentLine.LineNumber)) { documentLine = documentLine.PreviousLine; } l = BuildVisualLine(documentLine, globalTextRunProperties, paragraphProperties, _elementGenerators.ToArray(), _lineTransformers.ToArray(), _lastAvailableSize); _allVisualLines.Add(l); // update all visual top values (building the line might have changed visual top of other lines due to word wrapping) foreach (var line in _allVisualLines) { line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine); } } return l; } #endregion #region Visual Lines (fields and properties) private List<VisualLine> _allVisualLines = new List<VisualLine>(); private ReadOnlyCollection<VisualLine> _visibleVisualLines; private double _clippedPixelsOnTop; private List<VisualLine> _newVisualLines; /// <summary> /// Gets the currently visible visual lines. /// </summary> /// <exception cref="VisualLinesInvalidException"> /// Gets thrown if there are invalid visual lines when this property is accessed. /// You can use the <see cref="VisualLinesValid"/> property to check for this case, /// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines /// when they are invalid. /// </exception> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public ReadOnlyCollection<VisualLine> VisualLines { get { if (_visibleVisualLines == null) throw new VisualLinesInvalidException(); return _visibleVisualLines; } } /// <summary> /// Gets whether the visual lines are valid. /// Will return false after a call to Redraw(). /// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/> /// if this property is <c>false</c>. /// </summary> public bool VisualLinesValid => _visibleVisualLines != null; /// <summary> /// Occurs when the TextView is about to be measured and will regenerate its visual lines. /// This event may be used to mark visual lines as invalid that would otherwise be reused. /// </summary> public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting; /// <summary> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); maxWidth += AdditionalHorizontalScrollAmount; var heightTreeHeight = DocumentHeight; var options = Options; double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight); double extraHeightToAllowScrollBelowDocument = 0; if (options.AllowScrollBelowDocument) { if (!double.IsInfinity(_scrollViewport.Height)) { // HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after // scrolling to the very bottom. var minVisibleDocumentHeight = DefaultLineHeight; // increase the extend height to allow scrolling below the document extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight; } } TextLayer.SetVisualLines(_visibleVisualLines); SetScrollData(availableSize, new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument), _scrollOffset); VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight); } /// <summary> /// Build all VisualLines in the visible range. /// </summary> /// <returns>Width the longest line</returns> private double CreateAndMeasureVisualLines(Size availableSize) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); //Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset); var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y); // number of pixels clipped from the first visual line(s) _clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView); // clippedPixelsOnTop should be >= 0, except for floating point inaccurracy. Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon); _newVisualLines = new List<VisualLine>(); VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView)); var elementGeneratorsArray = _elementGenerators.ToArray(); var lineTransformersArray = _lineTransformers.ToArray(); var nextLine = firstLineInView; double maxWidth = 0; var yPos = -_clippedPixelsOnTop; while (yPos < availableSize.Height && nextLine != null) { var visualLine = GetVisualLine(nextLine.LineNumber) ?? BuildVisualLine(nextLine, globalTextRunProperties, paragraphProperties, elementGeneratorsArray, lineTransformersArray, availableSize); visualLine.VisualTop = _scrollOffset.Y + yPos; nextLine = visualLine.LastDocumentLine.NextLine; yPos += visualLine.Height; foreach (var textLine in visualLine.TextLines) { if (textLine.WidthIncludingTrailingWhitespace > maxWidth) maxWidth = textLine.WidthIncludingTrailingWhitespace; } _newVisualLines.Add(visualLine); } foreach (var line in _allVisualLines) { Debug.Assert(line.IsDisposed == false); if (!_newVisualLines.Contains(line)) DisposeVisualLine(line); } _allVisualLines = _newVisualLines; // visibleVisualLines = readonly copy of visual lines _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray()); _newVisualLines = null; if (_allVisualLines.Any(line => line.IsDisposed)) { throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" + "This can happen when Redraw() is called during measure for lines " + "that are already constructed."); } return maxWidth; } #endregion #region BuildVisualLine private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<IVisualLineTransformer> lineTransformersArray, Size availableSize) { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); //Debug.WriteLine("Building line " + documentLine.LineNumber); VisualLine visualLine = new VisualLine(this, documentLine); VisualLineTextSource textSource = new VisualLineTextSource(visualLine) { Document = _document, GlobalTextRunProperties = globalTextRunProperties, TextView = this }; visualLine.ConstructVisualElements(textSource, elementGeneratorsArray); if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine) { // Check whether the lines are collapsed correctly: double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine); double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine); if (!firstLinePos.IsClose(lastLinePos)) { for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++) { if (!_heightTree.GetIsCollapsed(i)) throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed."); } throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?"); } } visualLine.RunTransformers(textSource, lineTransformersArray); // now construct textLines: TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( textSource, textOffset, availableSize.Width, paragraphProperties, lastLineBreak ); textLines.Add(textLine); textOffset += textLine.Length; // exit loop so that we don't do the indentation calculation if there's only a single line if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker) break; if (paragraphProperties.firstLineInParagraph) { paragraphProperties.firstLineInParagraph = false; TextEditorOptions options = this.Options; double indentation = 0; if (options.InheritWordWrapIndentation) { // determine indentation for next line: int indentVisualColumn = GetIndentationVisualColumn(visualLine); if (indentVisualColumn > 0 && indentVisualColumn < textOffset) { indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0)); } } indentation += options.WordWrapIndentation; // apply the calculated indentation unless it's more than half of the text editor size: if (indentation > 0 && indentation * 2 < availableSize.Width) paragraphProperties.indent = indentation; } lastLineBreak = textLine.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var element = visualLine.Elements[elementIndex]; while (element.IsWhitespace(column)) { column++; if (column == element.VisualColumn + element.VisualLength) { elementIndex++; if (elementIndex == visualLine.Elements.Count) break; element = visualLine.Elements[elementIndex]; } } return column; } #endregion #region Arrange /// <summary> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } startVc = element.VisualColumn; length = element.DocumentLength; currentBrush = element.BackgroundBrush; } else { length += element.VisualLength; } } if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> /// Gets the vertical scroll offset. /// </summary> public double VerticalOffset => _scrollOffset.Y; /// <summary> /// Gets the scroll offset; /// </summary> public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); } } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation. /// <summary> /// Gets the width of a 'wide space' (the space width used for calculating the tab size). /// </summary> /// <remarks> /// This is the width of an 'x' in the current font. /// We do not measure the width of an actual space as that would lead to tiny tabs in /// some proportional fonts. /// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width. /// </remarks> public double WideSpaceWidth { get { CalculateDefaultTextMetrics(); return _wideSpaceWidth; } } /// <summary> /// Gets the default line height. This is the height of an empty line or a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different line height. /// </summary> public double DefaultLineHeight { get { CalculateDefaultTextMetrics(); return _defaultLineHeight; } } /// <summary> /// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/> /// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different baseline. /// </summary> public double DefaultBaseline { get { CalculateDefaultTextMetrics(); return _defaultBaseline; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); var line = _formatter.FormatLine( new SimpleTextSource("x", textRunProperties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties }, null); _wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace); _defaultBaseline = Math.Max(1, line.Baseline); _defaultLineHeight = Math.Max(1, line.Height); } else { _wideSpaceWidth = FontSize / 2; _defaultBaseline = FontSize; _defaultLineHeight = FontSize + 3; } // Update heightTree.DefaultLineHeight, if a document is loaded. if (_heightTree != null) _heightTree.DefaultLineHeight = _defaultLineHeight; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(e); } } #endregion #region Getting elements from Visual Position /// <summary> /// Gets the visual line at the specified document position (relative to start of document). /// Returns null if there is no visual line for the position (e.g. the position is outside the visible /// text area). /// </summary> public VisualLine GetVisualLineFromVisualTop(double visualTop) { // TODO: change this method to also work outside the visible range - // required to make GetPosition work as expected! EnsureVisualLines(); foreach (var vl in VisualLines) { if (visualTop < vl.VisualTop) continue; if (visualTop < vl.VisualTop + vl.Height) return vl; } return null; } /// <summary> /// Gets the visual top position (relative to start of document) from a document line number. /// </summary> public double GetVisualTopByDocumentLine(int line) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) continue; return element; } } return null; } #endregion #region Visual Position <-> TextViewPosition /// <summary> /// Gets the visual position from a text view position. /// </summary> /// <param name="position">The text view position.</param> /// <param name="yPositionMode">The mode how to retrieve the Y position.</param> /// <returns>The position in device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is within a character, it is rounded to the next character boundary. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPosition(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is inside a character, the position in front of the character is returned. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPositionFloor(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <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 pointe 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); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #endregion /// <summary> /// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden /// and not used to start the generation of a <see cref="VisualLine"/>. /// </summary> /// <remarks> /// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span /// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding /// <see cref="VisualLineElementGenerator"/>. /// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>. /// /// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines /// N+1 to M. Do not collapse line N itself. /// /// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the /// <see cref="CollapsedLineSection"/> returned from this method. /// </remarks> public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.CollapseText(start, end); } /// <summary> /// Gets the height of the document. /// </summary> public double DocumentHeight => _heightTree?.TotalHeight ?? 0; /// <summary> /// Gets the document line at the specified visual position. /// </summary> public DocumentLine GetDocumentLineByVisualTop(double visualTop) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetLineByVisualPosition(visualTop); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge pull request #64 from siegfriedpammer/dev/siegfriedpammer/folding-element-fixes Folding element fixes <DFF> @@ -1316,6 +1316,8 @@ namespace AvaloniaEdit.Rendering internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { + // this is necessary so hit-testing works properly and events get tunneled to the TextView. + drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer)
2
Merge pull request #64 from siegfriedpammer/dev/siegfriedpammer/folding-element-fixes
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068146
<NME> TextView.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Rendering { /// <summary> /// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>. /// /// This is the heart of the text editor, this class controls the text rendering process. /// /// Taken as a standalone control, it's a text viewer without any editing capability. /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent, ILogicalScrollable { private EventHandler _scrollInvalidated; #region Constructor static TextView() { ClipToBoundsProperty.OverrideDefaultValue<TextView>(true); FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; /// <summary> /// Creates a new TextView instance. /// </summary> public TextView() { Services.AddService(this); TextLayer = new TextLayer(this); _elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed); _lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed); _backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed); _columnRulerRenderer = new ColumnRulerRenderer(this); _currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this); Options = new TextEditorOptions(); Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators Layers = new LayerCollection(this); InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace); _hoverLogic = new PointerHoverLogic(this); _hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent); _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } #endregion #region Document Property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = AvaloniaProperty.Register<TextView, TextDocument>("Document"); private TextDocument _document; private HeightTree _heightTree; /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } internal double FontSize { get => GetValue(TemplatedControl.FontSizeProperty); set => SetValue(TemplatedControl.FontSizeProperty, value); } internal FontFamily FontFamily { get => GetValue(TemplatedControl.FontFamilyProperty); set => SetValue(TemplatedControl.FontFamilyProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { _heightTree.Dispose(); _heightTree = null; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options 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); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); RemoveInlineObjects(visualLine); } #endregion #region Get(OrConstruct)VisualLine /// <summary> /// Gets the visual line that contains the document line with the specified number. /// Returns null if the document line is outside the visible range. /// </summary> public VisualLine GetVisualLine(int documentLineNumber) { // TODO: EnsureVisualLines() ? foreach (var visualLine in _allVisualLines) { Debug.Assert(visualLine.IsDisposed == false); var start = visualLine.FirstDocumentLine.LineNumber; var end = visualLine.LastDocumentLine.LineNumber; if (documentLineNumber >= start && documentLineNumber <= end) return visualLine; } return null; } /// <summary> /// Gets the visual line that contains the document line with the specified number. /// If that line is outside the visible range, a new VisualLine for that document line is constructed. /// </summary> public VisualLine GetOrConstructVisualLine(DocumentLine documentLine) { if (documentLine == null) throw new ArgumentNullException("documentLine"); if (!this.Document.Lines.Contains(documentLine)) throw new InvalidOperationException("Line belongs to wrong document"); VerifyAccess(); VisualLine l = GetVisualLine(documentLine.LineNumber); if (l == null) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); while (_heightTree.GetIsCollapsed(documentLine.LineNumber)) { documentLine = documentLine.PreviousLine; } l = BuildVisualLine(documentLine, globalTextRunProperties, paragraphProperties, _elementGenerators.ToArray(), _lineTransformers.ToArray(), _lastAvailableSize); _allVisualLines.Add(l); // update all visual top values (building the line might have changed visual top of other lines due to word wrapping) foreach (var line in _allVisualLines) { line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine); } } return l; } #endregion #region Visual Lines (fields and properties) private List<VisualLine> _allVisualLines = new List<VisualLine>(); private ReadOnlyCollection<VisualLine> _visibleVisualLines; private double _clippedPixelsOnTop; private List<VisualLine> _newVisualLines; /// <summary> /// Gets the currently visible visual lines. /// </summary> /// <exception cref="VisualLinesInvalidException"> /// Gets thrown if there are invalid visual lines when this property is accessed. /// You can use the <see cref="VisualLinesValid"/> property to check for this case, /// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines /// when they are invalid. /// </exception> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public ReadOnlyCollection<VisualLine> VisualLines { get { if (_visibleVisualLines == null) throw new VisualLinesInvalidException(); return _visibleVisualLines; } } /// <summary> /// Gets whether the visual lines are valid. /// Will return false after a call to Redraw(). /// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/> /// if this property is <c>false</c>. /// </summary> public bool VisualLinesValid => _visibleVisualLines != null; /// <summary> /// Occurs when the TextView is about to be measured and will regenerate its visual lines. /// This event may be used to mark visual lines as invalid that would otherwise be reused. /// </summary> public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting; /// <summary> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); maxWidth += AdditionalHorizontalScrollAmount; var heightTreeHeight = DocumentHeight; var options = Options; double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight); double extraHeightToAllowScrollBelowDocument = 0; if (options.AllowScrollBelowDocument) { if (!double.IsInfinity(_scrollViewport.Height)) { // HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after // scrolling to the very bottom. var minVisibleDocumentHeight = DefaultLineHeight; // increase the extend height to allow scrolling below the document extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight; } } TextLayer.SetVisualLines(_visibleVisualLines); SetScrollData(availableSize, new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument), _scrollOffset); VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight); } /// <summary> /// Build all VisualLines in the visible range. /// </summary> /// <returns>Width the longest line</returns> private double CreateAndMeasureVisualLines(Size availableSize) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); //Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset); var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y); // number of pixels clipped from the first visual line(s) _clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView); // clippedPixelsOnTop should be >= 0, except for floating point inaccurracy. Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon); _newVisualLines = new List<VisualLine>(); VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView)); var elementGeneratorsArray = _elementGenerators.ToArray(); var lineTransformersArray = _lineTransformers.ToArray(); var nextLine = firstLineInView; double maxWidth = 0; var yPos = -_clippedPixelsOnTop; while (yPos < availableSize.Height && nextLine != null) { var visualLine = GetVisualLine(nextLine.LineNumber) ?? BuildVisualLine(nextLine, globalTextRunProperties, paragraphProperties, elementGeneratorsArray, lineTransformersArray, availableSize); visualLine.VisualTop = _scrollOffset.Y + yPos; nextLine = visualLine.LastDocumentLine.NextLine; yPos += visualLine.Height; foreach (var textLine in visualLine.TextLines) { if (textLine.WidthIncludingTrailingWhitespace > maxWidth) maxWidth = textLine.WidthIncludingTrailingWhitespace; } _newVisualLines.Add(visualLine); } foreach (var line in _allVisualLines) { Debug.Assert(line.IsDisposed == false); if (!_newVisualLines.Contains(line)) DisposeVisualLine(line); } _allVisualLines = _newVisualLines; // visibleVisualLines = readonly copy of visual lines _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray()); _newVisualLines = null; if (_allVisualLines.Any(line => line.IsDisposed)) { throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" + "This can happen when Redraw() is called during measure for lines " + "that are already constructed."); } return maxWidth; } #endregion #region BuildVisualLine private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<IVisualLineTransformer> lineTransformersArray, Size availableSize) { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); //Debug.WriteLine("Building line " + documentLine.LineNumber); VisualLine visualLine = new VisualLine(this, documentLine); VisualLineTextSource textSource = new VisualLineTextSource(visualLine) { Document = _document, GlobalTextRunProperties = globalTextRunProperties, TextView = this }; visualLine.ConstructVisualElements(textSource, elementGeneratorsArray); if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine) { // Check whether the lines are collapsed correctly: double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine); double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine); if (!firstLinePos.IsClose(lastLinePos)) { for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++) { if (!_heightTree.GetIsCollapsed(i)) throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed."); } throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?"); } } visualLine.RunTransformers(textSource, lineTransformersArray); // now construct textLines: TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( textSource, textOffset, availableSize.Width, paragraphProperties, lastLineBreak ); textLines.Add(textLine); textOffset += textLine.Length; // exit loop so that we don't do the indentation calculation if there's only a single line if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker) break; if (paragraphProperties.firstLineInParagraph) { paragraphProperties.firstLineInParagraph = false; TextEditorOptions options = this.Options; double indentation = 0; if (options.InheritWordWrapIndentation) { // determine indentation for next line: int indentVisualColumn = GetIndentationVisualColumn(visualLine); if (indentVisualColumn > 0 && indentVisualColumn < textOffset) { indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0)); } } indentation += options.WordWrapIndentation; // apply the calculated indentation unless it's more than half of the text editor size: if (indentation > 0 && indentation * 2 < availableSize.Width) paragraphProperties.indent = indentation; } lastLineBreak = textLine.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var element = visualLine.Elements[elementIndex]; while (element.IsWhitespace(column)) { column++; if (column == element.VisualColumn + element.VisualLength) { elementIndex++; if (elementIndex == visualLine.Elements.Count) break; element = visualLine.Elements[elementIndex]; } } return column; } #endregion #region Arrange /// <summary> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } startVc = element.VisualColumn; length = element.DocumentLength; currentBrush = element.BackgroundBrush; } else { length += element.VisualLength; } } if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> /// Gets the vertical scroll offset. /// </summary> public double VerticalOffset => _scrollOffset.Y; /// <summary> /// Gets the scroll offset; /// </summary> public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); } } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation. /// <summary> /// Gets the width of a 'wide space' (the space width used for calculating the tab size). /// </summary> /// <remarks> /// This is the width of an 'x' in the current font. /// We do not measure the width of an actual space as that would lead to tiny tabs in /// some proportional fonts. /// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width. /// </remarks> public double WideSpaceWidth { get { CalculateDefaultTextMetrics(); return _wideSpaceWidth; } } /// <summary> /// Gets the default line height. This is the height of an empty line or a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different line height. /// </summary> public double DefaultLineHeight { get { CalculateDefaultTextMetrics(); return _defaultLineHeight; } } /// <summary> /// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/> /// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different baseline. /// </summary> public double DefaultBaseline { get { CalculateDefaultTextMetrics(); return _defaultBaseline; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); var line = _formatter.FormatLine( new SimpleTextSource("x", textRunProperties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties }, null); _wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace); _defaultBaseline = Math.Max(1, line.Baseline); _defaultLineHeight = Math.Max(1, line.Height); } else { _wideSpaceWidth = FontSize / 2; _defaultBaseline = FontSize; _defaultLineHeight = FontSize + 3; } // Update heightTree.DefaultLineHeight, if a document is loaded. if (_heightTree != null) _heightTree.DefaultLineHeight = _defaultLineHeight; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(e); } } #endregion #region Getting elements from Visual Position /// <summary> /// Gets the visual line at the specified document position (relative to start of document). /// Returns null if there is no visual line for the position (e.g. the position is outside the visible /// text area). /// </summary> public VisualLine GetVisualLineFromVisualTop(double visualTop) { // TODO: change this method to also work outside the visible range - // required to make GetPosition work as expected! EnsureVisualLines(); foreach (var vl in VisualLines) { if (visualTop < vl.VisualTop) continue; if (visualTop < vl.VisualTop + vl.Height) return vl; } return null; } /// <summary> /// Gets the visual top position (relative to start of document) from a document line number. /// </summary> public double GetVisualTopByDocumentLine(int line) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) continue; return element; } } return null; } #endregion #region Visual Position <-> TextViewPosition /// <summary> /// Gets the visual position from a text view position. /// </summary> /// <param name="position">The text view position.</param> /// <param name="yPositionMode">The mode how to retrieve the Y position.</param> /// <returns>The position in device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is within a character, it is rounded to the next character boundary. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPosition(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is inside a character, the position in front of the character is returned. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPositionFloor(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <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 pointe 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); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #endregion /// <summary> /// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden /// and not used to start the generation of a <see cref="VisualLine"/>. /// </summary> /// <remarks> /// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span /// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding /// <see cref="VisualLineElementGenerator"/>. /// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>. /// /// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines /// N+1 to M. Do not collapse line N itself. /// /// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the /// <see cref="CollapsedLineSection"/> returned from this method. /// </remarks> public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.CollapseText(start, end); } /// <summary> /// Gets the height of the document. /// </summary> public double DocumentHeight => _heightTree?.TotalHeight ?? 0; /// <summary> /// Gets the document line at the specified visual position. /// </summary> public DocumentLine GetDocumentLineByVisualTop(double visualTop) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetLineByVisualPosition(visualTop); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge pull request #64 from siegfriedpammer/dev/siegfriedpammer/folding-element-fixes Folding element fixes <DFF> @@ -1316,6 +1316,8 @@ namespace AvaloniaEdit.Rendering internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { + // this is necessary so hit-testing works properly and events get tunneled to the TextView. + drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer)
2
Merge pull request #64 from siegfriedpammer/dev/siegfriedpammer/folding-element-fixes
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068147
<NME> TextView.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Rendering { /// <summary> /// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>. /// /// This is the heart of the text editor, this class controls the text rendering process. /// /// Taken as a standalone control, it's a text viewer without any editing capability. /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent, ILogicalScrollable { private EventHandler _scrollInvalidated; #region Constructor static TextView() { ClipToBoundsProperty.OverrideDefaultValue<TextView>(true); FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; /// <summary> /// Creates a new TextView instance. /// </summary> public TextView() { Services.AddService(this); TextLayer = new TextLayer(this); _elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed); _lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed); _backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed); _columnRulerRenderer = new ColumnRulerRenderer(this); _currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this); Options = new TextEditorOptions(); Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators Layers = new LayerCollection(this); InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace); _hoverLogic = new PointerHoverLogic(this); _hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent); _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } #endregion #region Document Property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = AvaloniaProperty.Register<TextView, TextDocument>("Document"); private TextDocument _document; private HeightTree _heightTree; /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } internal double FontSize { get => GetValue(TemplatedControl.FontSizeProperty); set => SetValue(TemplatedControl.FontSizeProperty, value); } internal FontFamily FontFamily { get => GetValue(TemplatedControl.FontFamilyProperty); set => SetValue(TemplatedControl.FontFamilyProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { _heightTree.Dispose(); _heightTree = null; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options 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); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); RemoveInlineObjects(visualLine); } #endregion #region Get(OrConstruct)VisualLine /// <summary> /// Gets the visual line that contains the document line with the specified number. /// Returns null if the document line is outside the visible range. /// </summary> public VisualLine GetVisualLine(int documentLineNumber) { // TODO: EnsureVisualLines() ? foreach (var visualLine in _allVisualLines) { Debug.Assert(visualLine.IsDisposed == false); var start = visualLine.FirstDocumentLine.LineNumber; var end = visualLine.LastDocumentLine.LineNumber; if (documentLineNumber >= start && documentLineNumber <= end) return visualLine; } return null; } /// <summary> /// Gets the visual line that contains the document line with the specified number. /// If that line is outside the visible range, a new VisualLine for that document line is constructed. /// </summary> public VisualLine GetOrConstructVisualLine(DocumentLine documentLine) { if (documentLine == null) throw new ArgumentNullException("documentLine"); if (!this.Document.Lines.Contains(documentLine)) throw new InvalidOperationException("Line belongs to wrong document"); VerifyAccess(); VisualLine l = GetVisualLine(documentLine.LineNumber); if (l == null) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); while (_heightTree.GetIsCollapsed(documentLine.LineNumber)) { documentLine = documentLine.PreviousLine; } l = BuildVisualLine(documentLine, globalTextRunProperties, paragraphProperties, _elementGenerators.ToArray(), _lineTransformers.ToArray(), _lastAvailableSize); _allVisualLines.Add(l); // update all visual top values (building the line might have changed visual top of other lines due to word wrapping) foreach (var line in _allVisualLines) { line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine); } } return l; } #endregion #region Visual Lines (fields and properties) private List<VisualLine> _allVisualLines = new List<VisualLine>(); private ReadOnlyCollection<VisualLine> _visibleVisualLines; private double _clippedPixelsOnTop; private List<VisualLine> _newVisualLines; /// <summary> /// Gets the currently visible visual lines. /// </summary> /// <exception cref="VisualLinesInvalidException"> /// Gets thrown if there are invalid visual lines when this property is accessed. /// You can use the <see cref="VisualLinesValid"/> property to check for this case, /// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines /// when they are invalid. /// </exception> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public ReadOnlyCollection<VisualLine> VisualLines { get { if (_visibleVisualLines == null) throw new VisualLinesInvalidException(); return _visibleVisualLines; } } /// <summary> /// Gets whether the visual lines are valid. /// Will return false after a call to Redraw(). /// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/> /// if this property is <c>false</c>. /// </summary> public bool VisualLinesValid => _visibleVisualLines != null; /// <summary> /// Occurs when the TextView is about to be measured and will regenerate its visual lines. /// This event may be used to mark visual lines as invalid that would otherwise be reused. /// </summary> public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting; /// <summary> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); maxWidth += AdditionalHorizontalScrollAmount; var heightTreeHeight = DocumentHeight; var options = Options; double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight); double extraHeightToAllowScrollBelowDocument = 0; if (options.AllowScrollBelowDocument) { if (!double.IsInfinity(_scrollViewport.Height)) { // HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after // scrolling to the very bottom. var minVisibleDocumentHeight = DefaultLineHeight; // increase the extend height to allow scrolling below the document extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight; } } TextLayer.SetVisualLines(_visibleVisualLines); SetScrollData(availableSize, new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument), _scrollOffset); VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight); } /// <summary> /// Build all VisualLines in the visible range. /// </summary> /// <returns>Width the longest line</returns> private double CreateAndMeasureVisualLines(Size availableSize) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); //Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset); var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y); // number of pixels clipped from the first visual line(s) _clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView); // clippedPixelsOnTop should be >= 0, except for floating point inaccurracy. Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon); _newVisualLines = new List<VisualLine>(); VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView)); var elementGeneratorsArray = _elementGenerators.ToArray(); var lineTransformersArray = _lineTransformers.ToArray(); var nextLine = firstLineInView; double maxWidth = 0; var yPos = -_clippedPixelsOnTop; while (yPos < availableSize.Height && nextLine != null) { var visualLine = GetVisualLine(nextLine.LineNumber) ?? BuildVisualLine(nextLine, globalTextRunProperties, paragraphProperties, elementGeneratorsArray, lineTransformersArray, availableSize); visualLine.VisualTop = _scrollOffset.Y + yPos; nextLine = visualLine.LastDocumentLine.NextLine; yPos += visualLine.Height; foreach (var textLine in visualLine.TextLines) { if (textLine.WidthIncludingTrailingWhitespace > maxWidth) maxWidth = textLine.WidthIncludingTrailingWhitespace; } _newVisualLines.Add(visualLine); } foreach (var line in _allVisualLines) { Debug.Assert(line.IsDisposed == false); if (!_newVisualLines.Contains(line)) DisposeVisualLine(line); } _allVisualLines = _newVisualLines; // visibleVisualLines = readonly copy of visual lines _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray()); _newVisualLines = null; if (_allVisualLines.Any(line => line.IsDisposed)) { throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" + "This can happen when Redraw() is called during measure for lines " + "that are already constructed."); } return maxWidth; } #endregion #region BuildVisualLine private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<IVisualLineTransformer> lineTransformersArray, Size availableSize) { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); //Debug.WriteLine("Building line " + documentLine.LineNumber); VisualLine visualLine = new VisualLine(this, documentLine); VisualLineTextSource textSource = new VisualLineTextSource(visualLine) { Document = _document, GlobalTextRunProperties = globalTextRunProperties, TextView = this }; visualLine.ConstructVisualElements(textSource, elementGeneratorsArray); if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine) { // Check whether the lines are collapsed correctly: double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine); double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine); if (!firstLinePos.IsClose(lastLinePos)) { for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++) { if (!_heightTree.GetIsCollapsed(i)) throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed."); } throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?"); } } visualLine.RunTransformers(textSource, lineTransformersArray); // now construct textLines: TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( textSource, textOffset, availableSize.Width, paragraphProperties, lastLineBreak ); textLines.Add(textLine); textOffset += textLine.Length; // exit loop so that we don't do the indentation calculation if there's only a single line if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker) break; if (paragraphProperties.firstLineInParagraph) { paragraphProperties.firstLineInParagraph = false; TextEditorOptions options = this.Options; double indentation = 0; if (options.InheritWordWrapIndentation) { // determine indentation for next line: int indentVisualColumn = GetIndentationVisualColumn(visualLine); if (indentVisualColumn > 0 && indentVisualColumn < textOffset) { indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0)); } } indentation += options.WordWrapIndentation; // apply the calculated indentation unless it's more than half of the text editor size: if (indentation > 0 && indentation * 2 < availableSize.Width) paragraphProperties.indent = indentation; } lastLineBreak = textLine.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var element = visualLine.Elements[elementIndex]; while (element.IsWhitespace(column)) { column++; if (column == element.VisualColumn + element.VisualLength) { elementIndex++; if (elementIndex == visualLine.Elements.Count) break; element = visualLine.Elements[elementIndex]; } } return column; } #endregion #region Arrange /// <summary> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } startVc = element.VisualColumn; length = element.DocumentLength; currentBrush = element.BackgroundBrush; } else { length += element.VisualLength; } } if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> /// Gets the vertical scroll offset. /// </summary> public double VerticalOffset => _scrollOffset.Y; /// <summary> /// Gets the scroll offset; /// </summary> public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); } } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation. /// <summary> /// Gets the width of a 'wide space' (the space width used for calculating the tab size). /// </summary> /// <remarks> /// This is the width of an 'x' in the current font. /// We do not measure the width of an actual space as that would lead to tiny tabs in /// some proportional fonts. /// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width. /// </remarks> public double WideSpaceWidth { get { CalculateDefaultTextMetrics(); return _wideSpaceWidth; } } /// <summary> /// Gets the default line height. This is the height of an empty line or a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different line height. /// </summary> public double DefaultLineHeight { get { CalculateDefaultTextMetrics(); return _defaultLineHeight; } } /// <summary> /// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/> /// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different baseline. /// </summary> public double DefaultBaseline { get { CalculateDefaultTextMetrics(); return _defaultBaseline; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); var line = _formatter.FormatLine( new SimpleTextSource("x", textRunProperties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties }, null); _wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace); _defaultBaseline = Math.Max(1, line.Baseline); _defaultLineHeight = Math.Max(1, line.Height); } else { _wideSpaceWidth = FontSize / 2; _defaultBaseline = FontSize; _defaultLineHeight = FontSize + 3; } // Update heightTree.DefaultLineHeight, if a document is loaded. if (_heightTree != null) _heightTree.DefaultLineHeight = _defaultLineHeight; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(e); } } #endregion #region Getting elements from Visual Position /// <summary> /// Gets the visual line at the specified document position (relative to start of document). /// Returns null if there is no visual line for the position (e.g. the position is outside the visible /// text area). /// </summary> public VisualLine GetVisualLineFromVisualTop(double visualTop) { // TODO: change this method to also work outside the visible range - // required to make GetPosition work as expected! EnsureVisualLines(); foreach (var vl in VisualLines) { if (visualTop < vl.VisualTop) continue; if (visualTop < vl.VisualTop + vl.Height) return vl; } return null; } /// <summary> /// Gets the visual top position (relative to start of document) from a document line number. /// </summary> public double GetVisualTopByDocumentLine(int line) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) continue; return element; } } return null; } #endregion #region Visual Position <-> TextViewPosition /// <summary> /// Gets the visual position from a text view position. /// </summary> /// <param name="position">The text view position.</param> /// <param name="yPositionMode">The mode how to retrieve the Y position.</param> /// <returns>The position in device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is within a character, it is rounded to the next character boundary. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPosition(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is inside a character, the position in front of the character is returned. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPositionFloor(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <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 pointe 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); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #endregion /// <summary> /// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden /// and not used to start the generation of a <see cref="VisualLine"/>. /// </summary> /// <remarks> /// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span /// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding /// <see cref="VisualLineElementGenerator"/>. /// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>. /// /// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines /// N+1 to M. Do not collapse line N itself. /// /// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the /// <see cref="CollapsedLineSection"/> returned from this method. /// </remarks> public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.CollapseText(start, end); } /// <summary> /// Gets the height of the document. /// </summary> public double DocumentHeight => _heightTree?.TotalHeight ?? 0; /// <summary> /// Gets the document line at the specified visual position. /// </summary> public DocumentLine GetDocumentLineByVisualTop(double visualTop) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetLineByVisualPosition(visualTop); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge pull request #64 from siegfriedpammer/dev/siegfriedpammer/folding-element-fixes Folding element fixes <DFF> @@ -1316,6 +1316,8 @@ namespace AvaloniaEdit.Rendering internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { + // this is necessary so hit-testing works properly and events get tunneled to the TextView. + drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer)
2
Merge pull request #64 from siegfriedpammer/dev/siegfriedpammer/folding-element-fixes
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068148
<NME> TextView.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Rendering { /// <summary> /// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>. /// /// This is the heart of the text editor, this class controls the text rendering process. /// /// Taken as a standalone control, it's a text viewer without any editing capability. /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent, ILogicalScrollable { private EventHandler _scrollInvalidated; #region Constructor static TextView() { ClipToBoundsProperty.OverrideDefaultValue<TextView>(true); FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; /// <summary> /// Creates a new TextView instance. /// </summary> public TextView() { Services.AddService(this); TextLayer = new TextLayer(this); _elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed); _lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed); _backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed); _columnRulerRenderer = new ColumnRulerRenderer(this); _currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this); Options = new TextEditorOptions(); Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators Layers = new LayerCollection(this); InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace); _hoverLogic = new PointerHoverLogic(this); _hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent); _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } #endregion #region Document Property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = AvaloniaProperty.Register<TextView, TextDocument>("Document"); private TextDocument _document; private HeightTree _heightTree; /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } internal double FontSize { get => GetValue(TemplatedControl.FontSizeProperty); set => SetValue(TemplatedControl.FontSizeProperty, value); } internal FontFamily FontFamily { get => GetValue(TemplatedControl.FontFamilyProperty); set => SetValue(TemplatedControl.FontFamilyProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { _heightTree.Dispose(); _heightTree = null; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options 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); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); RemoveInlineObjects(visualLine); } #endregion #region Get(OrConstruct)VisualLine /// <summary> /// Gets the visual line that contains the document line with the specified number. /// Returns null if the document line is outside the visible range. /// </summary> public VisualLine GetVisualLine(int documentLineNumber) { // TODO: EnsureVisualLines() ? foreach (var visualLine in _allVisualLines) { Debug.Assert(visualLine.IsDisposed == false); var start = visualLine.FirstDocumentLine.LineNumber; var end = visualLine.LastDocumentLine.LineNumber; if (documentLineNumber >= start && documentLineNumber <= end) return visualLine; } return null; } /// <summary> /// Gets the visual line that contains the document line with the specified number. /// If that line is outside the visible range, a new VisualLine for that document line is constructed. /// </summary> public VisualLine GetOrConstructVisualLine(DocumentLine documentLine) { if (documentLine == null) throw new ArgumentNullException("documentLine"); if (!this.Document.Lines.Contains(documentLine)) throw new InvalidOperationException("Line belongs to wrong document"); VerifyAccess(); VisualLine l = GetVisualLine(documentLine.LineNumber); if (l == null) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); while (_heightTree.GetIsCollapsed(documentLine.LineNumber)) { documentLine = documentLine.PreviousLine; } l = BuildVisualLine(documentLine, globalTextRunProperties, paragraphProperties, _elementGenerators.ToArray(), _lineTransformers.ToArray(), _lastAvailableSize); _allVisualLines.Add(l); // update all visual top values (building the line might have changed visual top of other lines due to word wrapping) foreach (var line in _allVisualLines) { line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine); } } return l; } #endregion #region Visual Lines (fields and properties) private List<VisualLine> _allVisualLines = new List<VisualLine>(); private ReadOnlyCollection<VisualLine> _visibleVisualLines; private double _clippedPixelsOnTop; private List<VisualLine> _newVisualLines; /// <summary> /// Gets the currently visible visual lines. /// </summary> /// <exception cref="VisualLinesInvalidException"> /// Gets thrown if there are invalid visual lines when this property is accessed. /// You can use the <see cref="VisualLinesValid"/> property to check for this case, /// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines /// when they are invalid. /// </exception> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public ReadOnlyCollection<VisualLine> VisualLines { get { if (_visibleVisualLines == null) throw new VisualLinesInvalidException(); return _visibleVisualLines; } } /// <summary> /// Gets whether the visual lines are valid. /// Will return false after a call to Redraw(). /// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/> /// if this property is <c>false</c>. /// </summary> public bool VisualLinesValid => _visibleVisualLines != null; /// <summary> /// Occurs when the TextView is about to be measured and will regenerate its visual lines. /// This event may be used to mark visual lines as invalid that would otherwise be reused. /// </summary> public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting; /// <summary> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); maxWidth += AdditionalHorizontalScrollAmount; var heightTreeHeight = DocumentHeight; var options = Options; double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight); double extraHeightToAllowScrollBelowDocument = 0; if (options.AllowScrollBelowDocument) { if (!double.IsInfinity(_scrollViewport.Height)) { // HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after // scrolling to the very bottom. var minVisibleDocumentHeight = DefaultLineHeight; // increase the extend height to allow scrolling below the document extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight; } } TextLayer.SetVisualLines(_visibleVisualLines); SetScrollData(availableSize, new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument), _scrollOffset); VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight); } /// <summary> /// Build all VisualLines in the visible range. /// </summary> /// <returns>Width the longest line</returns> private double CreateAndMeasureVisualLines(Size availableSize) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); //Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset); var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y); // number of pixels clipped from the first visual line(s) _clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView); // clippedPixelsOnTop should be >= 0, except for floating point inaccurracy. Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon); _newVisualLines = new List<VisualLine>(); VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView)); var elementGeneratorsArray = _elementGenerators.ToArray(); var lineTransformersArray = _lineTransformers.ToArray(); var nextLine = firstLineInView; double maxWidth = 0; var yPos = -_clippedPixelsOnTop; while (yPos < availableSize.Height && nextLine != null) { var visualLine = GetVisualLine(nextLine.LineNumber) ?? BuildVisualLine(nextLine, globalTextRunProperties, paragraphProperties, elementGeneratorsArray, lineTransformersArray, availableSize); visualLine.VisualTop = _scrollOffset.Y + yPos; nextLine = visualLine.LastDocumentLine.NextLine; yPos += visualLine.Height; foreach (var textLine in visualLine.TextLines) { if (textLine.WidthIncludingTrailingWhitespace > maxWidth) maxWidth = textLine.WidthIncludingTrailingWhitespace; } _newVisualLines.Add(visualLine); } foreach (var line in _allVisualLines) { Debug.Assert(line.IsDisposed == false); if (!_newVisualLines.Contains(line)) DisposeVisualLine(line); } _allVisualLines = _newVisualLines; // visibleVisualLines = readonly copy of visual lines _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray()); _newVisualLines = null; if (_allVisualLines.Any(line => line.IsDisposed)) { throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" + "This can happen when Redraw() is called during measure for lines " + "that are already constructed."); } return maxWidth; } #endregion #region BuildVisualLine private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<IVisualLineTransformer> lineTransformersArray, Size availableSize) { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); //Debug.WriteLine("Building line " + documentLine.LineNumber); VisualLine visualLine = new VisualLine(this, documentLine); VisualLineTextSource textSource = new VisualLineTextSource(visualLine) { Document = _document, GlobalTextRunProperties = globalTextRunProperties, TextView = this }; visualLine.ConstructVisualElements(textSource, elementGeneratorsArray); if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine) { // Check whether the lines are collapsed correctly: double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine); double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine); if (!firstLinePos.IsClose(lastLinePos)) { for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++) { if (!_heightTree.GetIsCollapsed(i)) throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed."); } throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?"); } } visualLine.RunTransformers(textSource, lineTransformersArray); // now construct textLines: TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( textSource, textOffset, availableSize.Width, paragraphProperties, lastLineBreak ); textLines.Add(textLine); textOffset += textLine.Length; // exit loop so that we don't do the indentation calculation if there's only a single line if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker) break; if (paragraphProperties.firstLineInParagraph) { paragraphProperties.firstLineInParagraph = false; TextEditorOptions options = this.Options; double indentation = 0; if (options.InheritWordWrapIndentation) { // determine indentation for next line: int indentVisualColumn = GetIndentationVisualColumn(visualLine); if (indentVisualColumn > 0 && indentVisualColumn < textOffset) { indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0)); } } indentation += options.WordWrapIndentation; // apply the calculated indentation unless it's more than half of the text editor size: if (indentation > 0 && indentation * 2 < availableSize.Width) paragraphProperties.indent = indentation; } lastLineBreak = textLine.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var element = visualLine.Elements[elementIndex]; while (element.IsWhitespace(column)) { column++; if (column == element.VisualColumn + element.VisualLength) { elementIndex++; if (elementIndex == visualLine.Elements.Count) break; element = visualLine.Elements[elementIndex]; } } return column; } #endregion #region Arrange /// <summary> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } startVc = element.VisualColumn; length = element.DocumentLength; currentBrush = element.BackgroundBrush; } else { length += element.VisualLength; } } if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> /// Gets the vertical scroll offset. /// </summary> public double VerticalOffset => _scrollOffset.Y; /// <summary> /// Gets the scroll offset; /// </summary> public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); } } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation. /// <summary> /// Gets the width of a 'wide space' (the space width used for calculating the tab size). /// </summary> /// <remarks> /// This is the width of an 'x' in the current font. /// We do not measure the width of an actual space as that would lead to tiny tabs in /// some proportional fonts. /// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width. /// </remarks> public double WideSpaceWidth { get { CalculateDefaultTextMetrics(); return _wideSpaceWidth; } } /// <summary> /// Gets the default line height. This is the height of an empty line or a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different line height. /// </summary> public double DefaultLineHeight { get { CalculateDefaultTextMetrics(); return _defaultLineHeight; } } /// <summary> /// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/> /// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different baseline. /// </summary> public double DefaultBaseline { get { CalculateDefaultTextMetrics(); return _defaultBaseline; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); var line = _formatter.FormatLine( new SimpleTextSource("x", textRunProperties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties }, null); _wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace); _defaultBaseline = Math.Max(1, line.Baseline); _defaultLineHeight = Math.Max(1, line.Height); } else { _wideSpaceWidth = FontSize / 2; _defaultBaseline = FontSize; _defaultLineHeight = FontSize + 3; } // Update heightTree.DefaultLineHeight, if a document is loaded. if (_heightTree != null) _heightTree.DefaultLineHeight = _defaultLineHeight; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(e); } } #endregion #region Getting elements from Visual Position /// <summary> /// Gets the visual line at the specified document position (relative to start of document). /// Returns null if there is no visual line for the position (e.g. the position is outside the visible /// text area). /// </summary> public VisualLine GetVisualLineFromVisualTop(double visualTop) { // TODO: change this method to also work outside the visible range - // required to make GetPosition work as expected! EnsureVisualLines(); foreach (var vl in VisualLines) { if (visualTop < vl.VisualTop) continue; if (visualTop < vl.VisualTop + vl.Height) return vl; } return null; } /// <summary> /// Gets the visual top position (relative to start of document) from a document line number. /// </summary> public double GetVisualTopByDocumentLine(int line) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) continue; return element; } } return null; } #endregion #region Visual Position <-> TextViewPosition /// <summary> /// Gets the visual position from a text view position. /// </summary> /// <param name="position">The text view position.</param> /// <param name="yPositionMode">The mode how to retrieve the Y position.</param> /// <returns>The position in device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is within a character, it is rounded to the next character boundary. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPosition(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is inside a character, the position in front of the character is returned. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPositionFloor(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <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 pointe 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); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #endregion /// <summary> /// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden /// and not used to start the generation of a <see cref="VisualLine"/>. /// </summary> /// <remarks> /// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span /// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding /// <see cref="VisualLineElementGenerator"/>. /// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>. /// /// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines /// N+1 to M. Do not collapse line N itself. /// /// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the /// <see cref="CollapsedLineSection"/> returned from this method. /// </remarks> public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.CollapseText(start, end); } /// <summary> /// Gets the height of the document. /// </summary> public double DocumentHeight => _heightTree?.TotalHeight ?? 0; /// <summary> /// Gets the document line at the specified visual position. /// </summary> public DocumentLine GetDocumentLineByVisualTop(double visualTop) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetLineByVisualPosition(visualTop); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge pull request #64 from siegfriedpammer/dev/siegfriedpammer/folding-element-fixes Folding element fixes <DFF> @@ -1316,6 +1316,8 @@ namespace AvaloniaEdit.Rendering internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { + // this is necessary so hit-testing works properly and events get tunneled to the TextView. + drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer)
2
Merge pull request #64 from siegfriedpammer/dev/siegfriedpammer/folding-element-fixes
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10068149
<NME> TextView.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Rendering { /// <summary> /// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>. /// /// This is the heart of the text editor, this class controls the text rendering process. /// /// Taken as a standalone control, it's a text viewer without any editing capability. /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent, ILogicalScrollable { private EventHandler _scrollInvalidated; #region Constructor static TextView() { ClipToBoundsProperty.OverrideDefaultValue<TextView>(true); FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; /// <summary> /// Creates a new TextView instance. /// </summary> public TextView() { Services.AddService(this); TextLayer = new TextLayer(this); _elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed); _lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed); _backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed); _columnRulerRenderer = new ColumnRulerRenderer(this); _currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this); Options = new TextEditorOptions(); Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators Layers = new LayerCollection(this); InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace); _hoverLogic = new PointerHoverLogic(this); _hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent); _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } #endregion #region Document Property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = AvaloniaProperty.Register<TextView, TextDocument>("Document"); private TextDocument _document; private HeightTree _heightTree; /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } internal double FontSize { get => GetValue(TemplatedControl.FontSizeProperty); set => SetValue(TemplatedControl.FontSizeProperty, value); } internal FontFamily FontFamily { get => GetValue(TemplatedControl.FontFamilyProperty); set => SetValue(TemplatedControl.FontFamilyProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { _heightTree.Dispose(); _heightTree = null; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options 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); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); RemoveInlineObjects(visualLine); } #endregion #region Get(OrConstruct)VisualLine /// <summary> /// Gets the visual line that contains the document line with the specified number. /// Returns null if the document line is outside the visible range. /// </summary> public VisualLine GetVisualLine(int documentLineNumber) { // TODO: EnsureVisualLines() ? foreach (var visualLine in _allVisualLines) { Debug.Assert(visualLine.IsDisposed == false); var start = visualLine.FirstDocumentLine.LineNumber; var end = visualLine.LastDocumentLine.LineNumber; if (documentLineNumber >= start && documentLineNumber <= end) return visualLine; } return null; } /// <summary> /// Gets the visual line that contains the document line with the specified number. /// If that line is outside the visible range, a new VisualLine for that document line is constructed. /// </summary> public VisualLine GetOrConstructVisualLine(DocumentLine documentLine) { if (documentLine == null) throw new ArgumentNullException("documentLine"); if (!this.Document.Lines.Contains(documentLine)) throw new InvalidOperationException("Line belongs to wrong document"); VerifyAccess(); VisualLine l = GetVisualLine(documentLine.LineNumber); if (l == null) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); while (_heightTree.GetIsCollapsed(documentLine.LineNumber)) { documentLine = documentLine.PreviousLine; } l = BuildVisualLine(documentLine, globalTextRunProperties, paragraphProperties, _elementGenerators.ToArray(), _lineTransformers.ToArray(), _lastAvailableSize); _allVisualLines.Add(l); // update all visual top values (building the line might have changed visual top of other lines due to word wrapping) foreach (var line in _allVisualLines) { line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine); } } return l; } #endregion #region Visual Lines (fields and properties) private List<VisualLine> _allVisualLines = new List<VisualLine>(); private ReadOnlyCollection<VisualLine> _visibleVisualLines; private double _clippedPixelsOnTop; private List<VisualLine> _newVisualLines; /// <summary> /// Gets the currently visible visual lines. /// </summary> /// <exception cref="VisualLinesInvalidException"> /// Gets thrown if there are invalid visual lines when this property is accessed. /// You can use the <see cref="VisualLinesValid"/> property to check for this case, /// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines /// when they are invalid. /// </exception> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public ReadOnlyCollection<VisualLine> VisualLines { get { if (_visibleVisualLines == null) throw new VisualLinesInvalidException(); return _visibleVisualLines; } } /// <summary> /// Gets whether the visual lines are valid. /// Will return false after a call to Redraw(). /// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/> /// if this property is <c>false</c>. /// </summary> public bool VisualLinesValid => _visibleVisualLines != null; /// <summary> /// Occurs when the TextView is about to be measured and will regenerate its visual lines. /// This event may be used to mark visual lines as invalid that would otherwise be reused. /// </summary> public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting; /// <summary> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); maxWidth += AdditionalHorizontalScrollAmount; var heightTreeHeight = DocumentHeight; var options = Options; double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight); double extraHeightToAllowScrollBelowDocument = 0; if (options.AllowScrollBelowDocument) { if (!double.IsInfinity(_scrollViewport.Height)) { // HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after // scrolling to the very bottom. var minVisibleDocumentHeight = DefaultLineHeight; // increase the extend height to allow scrolling below the document extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight; } } TextLayer.SetVisualLines(_visibleVisualLines); SetScrollData(availableSize, new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument), _scrollOffset); VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight); } /// <summary> /// Build all VisualLines in the visible range. /// </summary> /// <returns>Width the longest line</returns> private double CreateAndMeasureVisualLines(Size availableSize) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); //Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset); var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y); // number of pixels clipped from the first visual line(s) _clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView); // clippedPixelsOnTop should be >= 0, except for floating point inaccurracy. Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon); _newVisualLines = new List<VisualLine>(); VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView)); var elementGeneratorsArray = _elementGenerators.ToArray(); var lineTransformersArray = _lineTransformers.ToArray(); var nextLine = firstLineInView; double maxWidth = 0; var yPos = -_clippedPixelsOnTop; while (yPos < availableSize.Height && nextLine != null) { var visualLine = GetVisualLine(nextLine.LineNumber) ?? BuildVisualLine(nextLine, globalTextRunProperties, paragraphProperties, elementGeneratorsArray, lineTransformersArray, availableSize); visualLine.VisualTop = _scrollOffset.Y + yPos; nextLine = visualLine.LastDocumentLine.NextLine; yPos += visualLine.Height; foreach (var textLine in visualLine.TextLines) { if (textLine.WidthIncludingTrailingWhitespace > maxWidth) maxWidth = textLine.WidthIncludingTrailingWhitespace; } _newVisualLines.Add(visualLine); } foreach (var line in _allVisualLines) { Debug.Assert(line.IsDisposed == false); if (!_newVisualLines.Contains(line)) DisposeVisualLine(line); } _allVisualLines = _newVisualLines; // visibleVisualLines = readonly copy of visual lines _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray()); _newVisualLines = null; if (_allVisualLines.Any(line => line.IsDisposed)) { throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" + "This can happen when Redraw() is called during measure for lines " + "that are already constructed."); } return maxWidth; } #endregion #region BuildVisualLine private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<IVisualLineTransformer> lineTransformersArray, Size availableSize) { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); //Debug.WriteLine("Building line " + documentLine.LineNumber); VisualLine visualLine = new VisualLine(this, documentLine); VisualLineTextSource textSource = new VisualLineTextSource(visualLine) { Document = _document, GlobalTextRunProperties = globalTextRunProperties, TextView = this }; visualLine.ConstructVisualElements(textSource, elementGeneratorsArray); if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine) { // Check whether the lines are collapsed correctly: double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine); double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine); if (!firstLinePos.IsClose(lastLinePos)) { for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++) { if (!_heightTree.GetIsCollapsed(i)) throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed."); } throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?"); } } visualLine.RunTransformers(textSource, lineTransformersArray); // now construct textLines: TextLineBreak lastLineBreak = null; var textOffset = 0; var textLines = new List<TextLine>(); while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( textSource, textOffset, availableSize.Width, paragraphProperties, lastLineBreak ); textLines.Add(textLine); textOffset += textLine.Length; // exit loop so that we don't do the indentation calculation if there's only a single line if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker) break; if (paragraphProperties.firstLineInParagraph) { paragraphProperties.firstLineInParagraph = false; TextEditorOptions options = this.Options; double indentation = 0; if (options.InheritWordWrapIndentation) { // determine indentation for next line: int indentVisualColumn = GetIndentationVisualColumn(visualLine); if (indentVisualColumn > 0 && indentVisualColumn < textOffset) { indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0)); } } indentation += options.WordWrapIndentation; // apply the calculated indentation unless it's more than half of the text editor size: if (indentation > 0 && indentation * 2 < availableSize.Width) paragraphProperties.indent = indentation; } lastLineBreak = textLine.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var element = visualLine.Elements[elementIndex]; while (element.IsWhitespace(column)) { column++; if (column == element.VisualColumn + element.VisualLength) { elementIndex++; if (elementIndex == visualLine.Elements.Count) break; element = visualLine.Elements[elementIndex]; } } return column; } #endregion #region Arrange /// <summary> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) { ConnectToTextView(renderer); InvalidateLayer(renderer.Layer); } private void BackgroundRenderer_Removed(IBackgroundRenderer renderer) { DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } startVc = element.VisualColumn; length = element.DocumentLength; currentBrush = element.BackgroundBrush; } else { length += element.VisualLength; } } if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } return false; } private void OnScrollChange() { ((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty); } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. /// </summary> public double HorizontalOffset => _scrollOffset.X; /// <summary> /// Gets the vertical scroll offset. /// </summary> public double VerticalOffset => _scrollOffset.Y; /// <summary> /// Gets the scroll offset; /// </summary> public Vector ScrollOffset => _scrollOffset; /// <summary> /// Occurs when the scroll offset has changed. /// </summary> public event EventHandler ScrollOffsetChanged; private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); } } private bool _defaultTextMetricsValid; private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling. private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling. private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation. /// <summary> /// Gets the width of a 'wide space' (the space width used for calculating the tab size). /// </summary> /// <remarks> /// This is the width of an 'x' in the current font. /// We do not measure the width of an actual space as that would lead to tiny tabs in /// some proportional fonts. /// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width. /// </remarks> public double WideSpaceWidth { get { CalculateDefaultTextMetrics(); return _wideSpaceWidth; } } /// <summary> /// Gets the default line height. This is the height of an empty line or a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different line height. /// </summary> public double DefaultLineHeight { get { CalculateDefaultTextMetrics(); return _defaultLineHeight; } } /// <summary> /// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/> /// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different baseline. /// </summary> public double DefaultBaseline { get { CalculateDefaultTextMetrics(); return _defaultBaseline; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); var line = _formatter.FormatLine( new SimpleTextSource("x", textRunProperties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties }, null); _wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace); _defaultBaseline = Math.Max(1, line.Baseline); _defaultLineHeight = Math.Max(1, line.Height); } else { _wideSpaceWidth = FontSize / 2; _defaultBaseline = FontSize; _defaultLineHeight = FontSize + 3; } // Update heightTree.DefaultLineHeight, if a document is loaded. if (_heightTree != null) _heightTree.DefaultLineHeight = _defaultLineHeight; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> /// Updates the pointe cursor, but with background priority. /// </summary> public static void InvalidateCursor() { if (!_invalidCursor) { _invalidCursor = true; Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(e); } } #endregion #region Getting elements from Visual Position /// <summary> /// Gets the visual line at the specified document position (relative to start of document). /// Returns null if there is no visual line for the position (e.g. the position is outside the visible /// text area). /// </summary> public VisualLine GetVisualLineFromVisualTop(double visualTop) { // TODO: change this method to also work outside the visible range - // required to make GetPosition work as expected! EnsureVisualLines(); foreach (var vl in VisualLines) { if (visualTop < vl.VisualTop) continue; if (visualTop < vl.VisualTop + vl.Height) return vl; } return null; } /// <summary> /// Gets the visual top position (relative to start of document) from a document line number. /// </summary> public double GetVisualTopByDocumentLine(int line) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) continue; return element; } } return null; } #endregion #region Visual Position <-> TextViewPosition /// <summary> /// Gets the visual position from a text view position. /// </summary> /// <param name="position">The text view position.</param> /// <param name="yPositionMode">The mode how to retrieve the Y position.</param> /// <returns>The position in device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is within a character, it is rounded to the next character boundary. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPosition(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is inside a character, the position in front of the character is returned. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPositionFloor(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <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 pointe 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); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #endregion /// <summary> /// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden /// and not used to start the generation of a <see cref="VisualLine"/>. /// </summary> /// <remarks> /// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span /// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding /// <see cref="VisualLineElementGenerator"/>. /// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>. /// /// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines /// N+1 to M. Do not collapse line N itself. /// /// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the /// <see cref="CollapsedLineSection"/> returned from this method. /// </remarks> public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.CollapseText(start, end); } /// <summary> /// Gets the height of the document. /// </summary> public double DocumentHeight => _heightTree?.TotalHeight ?? 0; /// <summary> /// Gets the document line at the specified visual position. /// </summary> public DocumentLine GetDocumentLineByVisualTop(double visualTop) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetLineByVisualPosition(visualTop); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); return true; } IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) { return null; } event EventHandler ILogicalScrollable.ScrollInvalidated { add => _scrollInvalidated += value; remove => _scrollInvalidated -= value; } void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e) { _scrollInvalidated?.Invoke(this, e); } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public IPen ColumnRulerPen { get => GetValue(ColumnRulerPenProperty); set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; bool ILogicalScrollable.CanHorizontallyScroll { get => _canHorizontallyScroll; set { if (_canHorizontallyScroll != value) { _canHorizontallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.CanVerticallyScroll { get => _canVerticallyScroll; set { if (_canVerticallyScroll != value) { _canVerticallyScroll = value; ClearVisualLines(); InvalidateMeasure(); } } } bool ILogicalScrollable.IsLogicalScrollEnabled => true; Size ILogicalScrollable.ScrollSize => new Size(10, 50); Size ILogicalScrollable.PageScrollSize => new Size(10, 100); Size IScrollable.Extent => _scrollExtent; Vector IScrollable.Offset { get => _scrollOffset; set { value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); var isX = !_scrollOffset.X.IsClose(value.X); var isY = !_scrollOffset.Y.IsClose(value.Y); if (isX || isY) { SetScrollOffset(value); if (isX) { InvalidateVisual(); TextLayer.InvalidateVisual(); } InvalidateMeasure(); } } } Size IScrollable.Viewport => _scrollViewport; } } <MSG> Merge pull request #64 from siegfriedpammer/dev/siegfriedpammer/folding-element-fixes Folding element fixes <DFF> @@ -1316,6 +1316,8 @@ namespace AvaloniaEdit.Rendering internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { + // this is necessary so hit-testing works properly and events get tunneled to the TextView. + drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer)
2
Merge pull request #64 from siegfriedpammer/dev/siegfriedpammer/folding-element-fixes
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit